上几篇文章,主要学习了Extjs4 Grid的使用方法,从本篇开始,我们开始其他组件的学习,使用。在登录、注册甚至是发表文章或帖子的时候,都会用到验证码这个东西,那么在EXTJS中,可以使用验证码功能么?答案是肯定的,在EXTJS4之前,也有很多验证码的实现,在Extjs4中,验证码到底如何实现呢?
暂时,我们将验证码组件,命名为CheckCode。此组件继承自Ext.form.field.Text,在实现之前,我们需要写两个样式,分别用来控制验证码的输入框和验证码图片的大小。
CSS样式为:
- #CheckCode{float:left;}
- .x-form-code{width:73px;height:20px;vertical-align:middle;cursor:pointer;float:left;margin-left:7px;}
记住这两个样式的定义,后面,我们会用到它。
验证码的JS代码:
- Ext.define('SMS.view.CheckCode',{
- extend:'Ext.form.field.Text',
- alias:'widget.checkcode',
- inputTyle:'codefield',
- codeUrl:Ext.BLANK_IMAGE_URL,
- isLoader:true,
- onRender:function(ct,position){
- this.callParent(arguments);
- this.codeEl=ct.createChild({tag:'img',src:Ext.BLANK_IMAGE_URL});
- this.codeEl.addCls('x-form-code');
- this.codeEl.on('click',this.loadCodeImg,this);
- if(this.isLoader)this.loadCodeImg();
- },
- alignErrorIcon:function(){
- this.errorIcon.alignTo(this.codeEl,'tl-tr',[2,0]);
- },
-
- loadCodeImg:function(){
- this.codeEl.set({src:this.codeUrl+'?id='+Math.random()});
- }
-
- })
以上代码中,定义了一个“类”,名字是:SMS.view.CheckCode,其实这个名字,相当于extjs 3.x之中的命名空间,以前也提到过。它继承自Ext.form.field.Text,在它的onRender中,我们写了一些代码。其中this.callParent(arguments); 代替了xxxx.superclass.onRender.call(this, ct, position);在Ext.form.field.Text的基础上,使用createChild方法,创建了一个图片,并为其添加了一个名为x-form-code,而后,给其创建了一个click事件,这个事件实现的功能是,当我们点击验证码图片时,换另外一张图片,也就是常说的:“看不清?换一张功能。”,最后,如果isLoader为True时,调用loadCodeImg方法。至此,验证码功能全部完成了。下面,我们看看如何使用。
新建Login.js文件,定义“类”SMS.view.Login,其全部代码为:
- Ext.define('SMS.view.Login',{
- extend:'Ext.window.Window',
- alias:'widget.loginForm',
- requires:['Ext.form.*','SMS.view.CheckCode'],
- initComponent:function(){
- varcheckcode=Ext.create('SMS.view.CheckCode',{
- cls:'key',
- fieldLabel:'验证码',
- name:'CheckCode',
- id:'CheckCode',
- allowBlank:false,
- isLoader:true,
- blankText:'验证码不能为空',
- codeUrl:'/include/checkCode.asp',
- width:160
- })
- varform=Ext.widget('form',{
- border:false,
- bodyPadding:10,
- fieldDefaults:{
- labelAlign:'left',
- labelWidth:55,
- labelStyle:'font-weight:bold'
- },
- defaults:{
- margins:'00100'
- },
- items:[{
- xtype:'textfield',
- fieldLabel:'用户名',
- blankText:'用户名不能为空',
- allowBlank:false,
- width:240
- },{
- xtype:'textfield',
- fieldLabel:'密 码',
- allowBlank:false,
- blankText:'密码不能为空',
- width:240,
- inputType:'password'
- },checkcode],
- buttons:[{
- text:'登录',
- handler:function(){
- }
- },{
- text:'取消',
- handler:function(){
- }
- }]
- })
- Ext.apply(this,{
- height:160,
- width:280,
- title:'用户登陆',
- closeAction:'hide',
- closable:false,
- iconCls:'login',
- layout:'fit',
- modal:true,
- plain:true,
- resizable:false,
- items:form
- });
- this.callParent(arguments);
- }
- });
然后在主页面的代码中调用此LoginWindow。
- requires:['SMS.view.Login']
- varwin;
- win=Ext.create('SMS.view.Login').show();
最后效果图: