金額欄位後面要顯示「元」、數量欄位要顯示「公斤」,這是常見的介面需求。ExtJS 的 NumberField 本身沒有這個能力,但只要擴充 TextField 的 onRender,就能讓所有輸入框都支援單位顯示。
// 在輸入框(textfield)後方附加 unitText
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: 'div',
html: this.unitText
});
this.unitEl.addClass('x-form-unit');
// 依單位字串長度壓縮輸入框寬度,中文以兩個字元估算
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]);
};
}
}
});
<style>
.x-form-unit {
height: 22px;
line-height: 22px;
padding-left: 2px;
display: inline-block;
display: inline;
}
</style>
<script type="text/javascript" src="UnitText.js"></script>
var jine = new Ext.form.NumberField({
id: 'je',
fieldLabel: '金額',
allowDecimals: true, // 允許小數點
allowNegative: false, // 允許負數
width: 100,
style: 'text-align:right',
unitText: ' 元'
});
寬度補償那行用 replace(/[^\x00-\xff]/g, "xx") 把全形字元換成兩個半形字元來估算,是為了讓中英文混排的單位都能抓得準;6 這個係數則是經驗值,換字型時可能需要微調。
由於是透過 Ext.override 全域擴充,載入這個檔案後,所有 TextField 及其子類別(包含 NumberField)都會多出 unitText 設定,不特別指定的話就是空字串、維持原樣,不影響既有畫面。