带计数的textarea封装

分享 已结 3 249
Hide
Hide 2019-8-22
悬赏:20飞吻
//封装
$.fn.extend({
countBinding: function ()
{
var $this = $(this),
maxLen = parseInt($this.attr("autocnt-max")),// 取 autocnt-max 属性的值
$wrap = $("<div>", { "class": "text-countBox" }),
$content = $("<div>", { "class":"fr color-normal"}),
$cur = $("<span>").text($this.val().length),
$span = $("<span>").text("/"),
$max = $("<span>").text(maxLen);

if (!maxLen) { top.layer.msg("缺少必要属性maxlen"); return; }

$this.wrap($wrap);
$this.after($content.append($cur).append($span).append($max));

var fnCount = function () {
var val = $this.val();
if (val.length>= maxLen) {
$this.val(val.substr(0, maxLen));
$cur.addClass("color-red");
}
else
{
$cur.removeClass("color-red");
}
$cur.text($this.val().length);
};

if ('oninput' in document.createElement('div'))
{
$this.bind('input', function () {
fnCount();
});
}
else
{
$this.get(0).attachEvent('onpropertychange', function (event) {
if (event && event.propertyName == 'value') {
fnCount();
}
});
}

$this.change(function () {
fnCount();
});

}
});
html:


//部分公共 css代码
.fr{float:right;}
.color-normal{color:#9b9b9b;}
.color-red{color: #F50D45;}

-----------------------华丽的分割线------------------------------------------

//调用:$("[autocnt-max]").countBinding();//自动计数
界面:
回帖
  • 挺好,感谢分享
    1 回复
  • [good]
    0 回复
  • 如果重复打开关闭带有冲突的计数框就会重复append ,可以选择清空但是如果依然在重复打开关闭的前提下就会导致实时输入的计数会重复
    0 回复