查询输入框几乎是网站中必不可少的元素,在主流网站中,查询输入框的样式大体相同,例如CSDN主页右上方上的查询输入框。
近期由于项目的需要,本人动手实现了基于ExtJS框架的“标准”样式的查询输入框组件。
实现的效果如下:
组件代码如下:
Ext.define('Ext.ux.SearchInput', {
extend: 'Ext.Component',
alias: 'widget.searchinput',
emptyVal: 'Search',
inputCls: 'x-ux-input-search',
inputRadiusCls: 'x-ux-input-search-radius',
radiusFlag: false,
inputWidth: 170,
renderTpl: ['<input type="text" name="{inputName}" style="width:{inputWidth}px;" class="{inputCls}" value="{emptyVal}">'],
initComponent: function() {
this.callParent();
this.inputName = this.frameName || this.id + '-input';
this.addEvents('beforeaction');
Ext.apply(this.renderSelectors, {
inputEl: 'input'
});
},
initRenderData: function() {
var me = this,
inputCls = me.inputCls;
if (me.radiusFlag) {
inputCls = me.inputRadiusCls;
}
return Ext.apply(me.callParent(), {
inputName: me.inputName,
inputCls: inputCls,
emptyVal: me.emptyVal,
inputWidth: me.inputWidth
});
},
getInputDom: function() {
return this.inputEl.dom;
},
initEvents: function() {
var me = this,
inputEl = me.inputEl;
me.callParent();
inputEl.on('focus', me.onFocus, me);
inputEl.on('blur', me.onBlur, me);
if (!me.keyNav) {
me.keyNav = Ext.create('Ext.KeyNav', inputEl, {
'enter': me.onEnter,
scope: me
});
}
},
onFocus: function() {
var me = this,
inputEl = me.inputEl;
if (inputEl.getValue() == me.emptyVal) {
inputEl.dom.value = '';
}
inputEl.dom.style.color = '#7eadd9';
return true;
},
onBlur: function() {
var me = this,
inputEl = me.inputEl;
if (inputEl.getValue() == '') {
inputEl.dom.value = me.emptyVal;
}
inputEl.dom.style.color = '#b5b8c8';
return true;
},
onEnter: function() {
var me = this;
if (me.fireEvent('beforeaction', me) !== false) {
me.handler();
}
},
doAction: function() {
this.onEnter();
},
getValue: function() {
return this.inputEl.getValue();
},
onDestroy: function() {
var me = this,
inputEl = me.inputEl;
inputEl.clearListeners();
me.keyNav = null;
delete me.keyNav;
me.callParent();
}
});
使用示例如下:
Ext.create('Ext.ux.SearchInput', {
// 设置Input宽度
inputWidth: 220,
// 设置是否圆角
radiusFlag: false,
// 设置空提示
emptyVal: '搜索',
// 查询方法
handler: function() {
var me = this;
alert(me.getValue());
},
renderTo: Ext.getBody()
});
组件的实现比较简单,主要包含以下“注意点”:
1.监听Input标签元素的回车事件,通过配置组件的handler方法,执行回车查询动作。
2.提供doAction方法手动执行查询动作(即调用回车事件的实现方法)。
3.通过组件提供的getValue方法可以获取Input标签的value。
当然为了达到效果,你需要引入以下样式:
.x-ux-input-search {
height: 24px;
line-height: 22px;
border: solid 1px;
background: white url(input-search-icon.gif) no-repeat 99% 4px;
color: #b5b8c8;
vertical-align: middle;
margin: 2px;
}
.x-ux-input-search-radius {
height: 24px;
line-height: 22px;
border: solid 1px;
background: white url(input-search-icon.gif) no-repeat 99% 4px;
color: #b5b8c8;
vertical-align: middle;
margin: 2px;
border-radius: 5px;
}
其中的图片资源为:
本文第一次发表于:基于ExtJS框架的查询组件
更多ExtJS相关内容请点击:戴面罩的怪杰