textarea的字数限制

た 入场券 2022-06-01 13:49 552阅读 0赞

功能描述

在项目中我们经常会遇到要对textarea进行输入字符数的限制,并在下方提示共可输入多少文字,已输入多少,还可输入多少的类似功能。

所以就有了下面封装好的这个函数,不管是以那种方式输入,字数都可以完美的限制,可以点击此处查看例子。

代码

  1. /** * textarea的字符数限制 * @param {*} options * element [string] Dom对象的id * length [number] 可输入的总长度 * hadWrite [boolean] 是否显示已输入多少的内容,true显示,false不显示,默认为true * canWrite [boolean] 是否显示还可输入多少的内容,true显示,false不显示,默认为true */
  2. function textareaWriteLength(options) {
  3. var jsWriteBox = $(options.element).parentsUntil(".js-write-box").parent(".js-write-box");
  4. var jsAllWriteBox = jsWriteBox.find(".js-all-write-box"),
  5. jsHadWriteBox = jsWriteBox.find(".js-had-write-box"),
  6. jsCanWriteBox = jsWriteBox.find(".js-can-write-box");
  7. var jsAllWriteLength = jsWriteBox.find(".js-all-write-length"),
  8. jsHadWriteLength = jsWriteBox.find(".js-had-write-length"),
  9. jsCanWriteLength = jsWriteBox.find(".js-can-write-length");
  10. jsAllWriteLength.html(options.length);
  11. if (options.hadWrite && options.canWrite) {
  12. jsAllWriteBox.append('<span>,</span>');
  13. jsHadWriteBox.append('<span>,</span>').css("display", "inline");
  14. jsHadWriteLength.html(0);
  15. jsCanWriteBox.css("display", "inline");
  16. jsCanWriteLength.html(options.length);
  17. } else if (options.hadWrite) {
  18. jsAllWriteBox.append('<span>,</span>');
  19. jsHadWriteBox.append('<span>。</span>').css("display", "inline");
  20. jsHadWriteLength.html(0);
  21. } else if (options.canWrite) {
  22. jsAllWriteBox.append('<span>,</span>');
  23. jsCanWriteBox.css("display", "inline");
  24. jsCanWriteLength.html(options.length);
  25. } else {
  26. jsAllWriteBox.append('<span>。</span>');
  27. }
  28. function textareaWriteEvent() {
  29. console.log(1)
  30. var _this = $(this);
  31. var length = _this.val().length;
  32. if (length >= options.length) {
  33. _this.val(_this.val().substring(0, options.length));
  34. jsHadWriteLength.html(options.length);
  35. jsCanWriteLength.html(0);
  36. } else {
  37. jsHadWriteLength.html(length);
  38. jsCanWriteLength.html(options.length - length);
  39. }
  40. }
  41. $("body").on("input", options.element, textareaWriteEvent);
  42. }

参数说明


























参数 说明
element Dom对象的id
length 可输入的总长度
hadWrite 是否显示已输入多少的内容,true显示,false不显示
canWrite 是否显示还可输入多少的内容,true显示,false不显示

使用说明

  1. textareaWriteLength({ element: "#textareaWriteLength", length: 120, hadWrite: true, canWrite: true });

详情可查看: http://www.fxss5201.cn/project/html/textarea/textareaWriteLength/

发表评论

表情:
评论列表 (有 0 条评论,552人围观)

还没有评论,来说两句吧...

相关阅读

    相关 textarea字数限制

    功能描述 在项目中我们经常会遇到要对textarea进行输入字符数的限制,并在下方提示共可输入多少文字,已输入多少,还可输入多少的类似功能。 所以就有了下面封装好的这个