textarea的字数限制

57 篇文章 1 订阅
23 篇文章 0 订阅

功能描述

在项目中我们经常会遇到要对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('<span>,</span>');
        jsHadWriteBox.append('<span>,</span>').css("display", "inline");
        jsHadWriteLength.html(0);
        jsCanWriteBox.css("display", "inline");
        jsCanWriteLength.html(options.length);
    } else if (options.hadWrite) {
        jsAllWriteBox.append('<span>,</span>');
        jsHadWriteBox.append('<span>。</span>').css("display", "inline");
        jsHadWriteLength.html(0);
    } else if (options.canWrite) {
        jsAllWriteBox.append('<span>,</span>');
        jsCanWriteBox.css("display", "inline");
        jsCanWriteLength.html(options.length);
    } else {
        jsAllWriteBox.append('<span>。</span>');
    }

    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);
}

参数说明

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

使用说明

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值