我用它来检查textarea的最大长度,而不是使用IE8-9不支持的maxlength。
在IE8中如果我粘贴一个500字节的字符焦点在textarea元素上丢失。无法选择或删除该字符。
如何保持对元素的关注?
$('textarea[maxlength]').bind('keypress keydown keyup paste change', function(){
var element = this;
setTimeout(function() { //Get the value
var text = $(element).val();
var limit = $(element).attr('maxlength'); //Get the maxlength
length = new Number(text.length); //counter increase
counter = limit-length;
$('#feedbackNum_counter').text(counter);
//Check if the length exceeds what is permitted
if (text.length > limit) {
$(element).prop('readOnly',true);
$(element).val(text.substr(0, limit)); //Truncate the text if necessary
$('#feedbackNum_counter').text(0)
}
},1)
});
答案 0 :(得分:0)
这是一个简单的解决方案。
var maxLengthTAs = $("textarea[maxlength]");
for(var i = 0; i < maxLengthTAs.length; i++)
{
var _textArea = $(maxLengthTAs[i]);
var _maxLength = _textArea.attr("maxlength");
var _testString = "";
for(var c = 0; c < _maxLength+1; c++) _testString+=" ";
_textArea.val(_testString);
//Feature Detection
var _test = _textArea.val();
if(_test.length > _maxLength) {
//if it's over the max length, the feature is not present, hook up events
_textArea.keyup(function(){
var _max = $(this).attr("maxlength");
var _val = $(this).val().length;
if(_val > _max) $(this).val($(this).val().substr(0,_max));
});
}
_textArea.val("");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea maxlength='50' placeholder='Max 50 Characters'></textarea>
&#13;