核心提示:功能描述在项目中我们经常会遇到要对textarea进行输入字符数的限制,并在下方提示共可输入多少文字,已输入多少,还可输入多少的类似功能。所以就有了下面封装好的这个函数,不管是以那种方式输入,字数都可...
功能描述
在项目中我们经常会遇到要对textarea进行输入字符数的限制,并在下方提示共可输入多少文字,已输入多少,还可输入多少的类似功能。
所以就有了下面封装好的这个函数,不管是以那种方式输入,字数都可以完美的限制。
代码
/** * textarea的字符数限制 * @param {*} options * element [string] Dom对象的id * length [number] 可输入的总长度 * hadWrite [boolean] 是否显示已输入多少的内容,true显示,false不显示,默认为true * canWrite [boolean] 是否显示还可输入多少的内容,true显示,false不显示,默认为true */ function textareaWriteLength(options) { var jsWriteBox = $(options.element).parentsUntil(".js-write-box").parent(".js-write-box"); var jsAllWriteBox = jsWriteBox.find(".js-all-write-box"), jsHadWriteBox = jsWriteBox.find(".js-had-write-box"), jsCanWriteBox = jsWriteBox.find(".js-can-write-box"); var jsAllWriteLength = jsWriteBox.find(".js-all-write-length"), jsHadWriteLength = jsWriteBox.find(".js-had-write-length"), jsCanWriteLength = jsWriteBox.find(".js-can-write-length"); jsAllWriteLength.html(options.length); if (options.hadWrite && options.canWrite) { jsAllWriteBox.append(','); jsHadWriteBox.append(',').css("display", "inline"); jsHadWriteLength.html(0); jsCanWriteBox.css("display", "inline"); jsCanWriteLength.html(options.length); } else if (options.hadWrite) { jsAllWriteBox.append(','); jsHadWriteBox.append('。').css("display", "inline"); jsHadWriteLength.html(0); } else if (options.canWrite) { jsAllWriteBox.append(','); jsCanWriteBox.css("display", "inline"); jsCanWriteLength.html(options.length); } else { jsAllWriteBox.append('。'); } function textareaWriteEvent() { console.log(1) var _this = $(this); var length = _this.val().length; if (length >= options.length) { _this.val(_this.val().substring(0, options.length)); jsHadWriteLength.html(options.length); jsCanWriteLength.html(0); } else { jsHadWriteLength.html(length); jsCanWriteLength.html(options.length - length); } } $("body").on("input", options.element, textareaWriteEvent); }
参数说明
参数 | 说明 |
---|---|
element | Dom对象的id |
length | 可输入的总长度 |
hadWrite | 是否显示已输入多少的内容,true显示,false不显示 |
canWrite | 是否显示还可输入多少的内容,true显示,false不显示 |
使用说明
textareaWriteLength({ element: "#textareaWriteLength", length: 120, hadWrite: true, canWrite: true });