在一些流行的网站,比如 Twitter 等,当你在 Textarea 中输入文字,通常会有文字自动统计你已经输入了多少个字符,总计多少个字符,还能输入多少字符,这样的小提示,通常能增强用户体验,像 Twitter 这样限制 140 字的微博客站点,这个功能也变得必不可少。
而我现在正在做的一个项目,其中发送 SMS 的文本框,也必须要提示用户输入的字数,下面就是我的实现方式,采用的 Mootools。基本的计算都已经有了,只要稍作修改,比如限制文字长度,提示剩余多少文字等等,这样就可以拿到自己的项目中使用了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | <script language="Javascript"> //<[CDATA[ var Countable = new Class({ count: 0, sms_count: 0, hint_template: "一共輸入了 {count} 個字,需要 {sms_count} 則簡訊傳送", // 初始化 initialize: function(textareaId) { // 得到 Textarea 对象 input = $(textareaId); if (input) { // 创建一个提示信息对象 this.hint = new Element("div", { 'class': "hint" }); // 放到 textarea 的后面 this.hint.injectAfter(input); // 设置事件 input.addEvent('keydown', this.onKeyPress.bindWithEvent(this)); input.addEvent('keyup', this.onKeyPress.bindWithEvent(this)); // 设定 Input 为 Class 属性,方便其它方法中使用 this.input = input; // 有时候刷新页面时 Firefox 会莫名奇妙缓存 Textarea 中文字 // 这里调用一次 update(),计算被缓存的文字长度 this.count = input.value.length; if (this.count > 0) { this.sms_count = 1; this.update(); } } }, // 按键处理 onKeyPress: function(event) { event = new Event(event); // 当使用 Modifiter 组合键位时,停止计算 if(!event.shift && !event.control && !event.alt && !event.meta) { this.update(); } }, // 更新 update: function() { // 获得当前 Textarea 域中文字数 this.count = this.input.value.length; if (this.count > 0) { this.sms_count = 1; } // 临时的数字数组,用于替换模板 var foo = {count: this.count, sms_count: this.sms_count}; // 翻译文字模板,将 Html 文字信息嵌入到 Hint 层中 var hint_html = this.hint_template.substitute(foo); this.hint.innerHTML = hint_html; } }); /** * Startup */ window.addEvent('domready', function () { new Countable('sms_text'); }); </script> |