---
title: "文本输入框增加单位名称的方法-2010-1-13修正"
author: "simen_net"
date: "2009-12-21T16:42:22Z"
tags: []
categories: ["Web前端"]
slug: "2010-1-13"
draft: false
lastmod: "2010-01-13T11:49:33Z"
id: 552945
url: "https://simen-net.iteye.com/blog/552945"
---

先上效果，已在Firefox3.5、IE7、Chrome3中测试正常

完整应用和代码请转到 http://www.iteye.com/topic/553020

![](http://dl.iteye.com/upload/attachment/183344/91324337-c3c9-32bf-a1b6-05aeb4d5c263.jpg)

想达到这个效果，可惜ExtJS本身不支持，那么我们就来扩展吧

 

```
// 重写Ext.form.TextField的onRender方法以支持文本框后输入单位名称
Ext.override(Ext.form.TextField, {
      unitText : '',
      onRender : function(ct, position) {
        Ext.form.TextField.superclass.onRender.call(this, ct, position);
        // 如果单位字符串已定义 则在后方增加单位对象
        if (this.unitText != '') {
          this.unitEl = ct.createChild({
                tag : 'font',
                html : this.unitText
              });
          this.unitEl.addClass('x-form-unit');
          // 如果当前width存在（当定义为自动宽度或百分比时width不存在）则增加单位名称的同时 按单位名称大小减少文本框的长度
          if (typeof(this.width) != 'undefined' && this.width > 0) {
            this.width = this.width - (this.unitText.replace(/[^\x00-\xff]/g, "xx").length * 6 + 2);
          }
          // 同时修改错误提示图标的位置
          this.alignErrorIcon = function() {
            this.errorIcon.alignTo(this.unitEl, 'tl-tr', [2, 0]);
          };
        }
      }
    })
```

 同时要在css文件中增加

```
.x-form-unit {
	height: 22px;
	line-height: 22px;
	padding-left: 2px;
	display: inline-block;
	display: inline;
}

.x-form-field-wrap {
	float: left;
}
```

 这里要说明一下：IE的BUG，如果只有

```
display: inline-block;
```

 可惜只能在Firefox和Chrome浏览器，IE里面就成这样了

![](http://dl.iteye.com/upload/attachment/183346/10c28245-0a05-3010-8afb-ece75cb9991b.jpg)  
 所以必须是

```
	display: inline-block;
	display: inline;
```

 

注意事项：在实际使用中发现ExtJS中还有一些其他控件是继承了textfield，例如combo，目前使用的情况是在combo中能正常显示单位，其他的控件就没有一一测试。

 

combo的效果如下

![](http://dl.iteye.com/upload/attachment/183354/0b85bdb1-7f88-3ce2-bb30-b288836d5e7b.jpg)