`
yangyou230
  • 浏览: 1650401 次
文章分类
社区版块
存档分类

在IE中模拟textarea的maxlength属性

 
阅读更多
很可惜在IE中textarea不支持maxlength属性,当然其他浏览器都支持,maxlength for textarea是 HTML5 的新属性,详见:http://www.w3schools.com/html5/tag_textarea.asp

网上有很多例子模拟这个属性,但是大部分都是利用用户输入之后再判断是否超过maxlength,如果超过就去掉最后一部分文字。

这样做一方面是用户体验不是很好,用户可以看到他输入了一些字母但是马上又不见了;另一方面是用户可以在任何位置输入,去掉最后一部分就完全不对了。

我写的这个例子考虑了这些因素,通过preventDefault来真实的模拟,同时考虑keyup和copy事件。


there are many jquery addon to simulat that,but it is not very good, because they detect the length onkeyup, which you will see the letters you type first and then gets removed afterwards. some other example just remove the last character of the textarea and does not care where is your selection.


so we can use the following to simulate that:


$textarea.bind("keypress.formTextarea paste.formTextarea", function(event) {


if($.browser.msie && !options.bKeepTyping){
var $this = $(this);
var maxLength = $this.data(options.maxlengthData);
var currentLength = $this.val().length;
var remainLength = maxLength - currentLength;
var selectionLength = document.selection.createRange().text.length;


if(event.type == 'keypress'){
if(event.which > 32 && event.which < 127 && !event.metaKey && (remainLength <= 0) && selectionLength == 0){
return false;
}
}else if(event.type == 'paste'){
var pasteText = window.clipboardData.getData('Text');
if(currentLength - selectionLength + pasteText.length > maxLength){
window.clipboardData.setData('Text',pasteText.substring(0,maxLength -(currentLength - selectionLength) ))
}
}
}

});




another way is to make a clone to apply events on the clone
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics