问问题
1024 次
3 回答
3
这是 HTML5 的解决方案,IE9 或更早版本不支持(根据this):
<textarea maxlength="255"></textarea>
由于您可能无法放弃对 IE9(甚至可能是 IE8)的支持,因此建议您将其与 JavaScript 结合使用,以防止 textarea 上的keydown
和paste
事件的默认行为,正如 standup75 所建议的那样。
以下是使用纯 JavaScript 的方法:
<textarea id="txtarea" maxlength="255"></textarea>
<script>
var field = document.getElementById('txtarea');
if(field.addEventListener) {
field.addEventListener('keydown', enforceMaxlength);
field.addEventListener('paste', enforceMaxlength);
} else {
// IE6-8
field.attachEvent('onkeydown', enforceMaxlength);
field.attachEvent('onpaste', enforceMaxlength);
}
function enforceMaxlength(evt) {
var maxLength = 255;
if(this.value.length >= maxLength) {
evt.preventDefault()
}
}
</script>
于 2012-09-24T16:09:02.260 回答
2
HTML5 提供了 maxLength 属性。否则,你需要一些 javascript,在 jQuery 中,你会做类似的事情
maxLength = 50;
$("textarea").on("keydown paste", function(e){
if ($(this).val().length>=maxLength) e.preventDefault();
});
于 2012-09-24T16:10:17.857 回答
2
您可以使用maxlength="255"
(它指定元素中允许的最大字符数。)
或者你也可以通过 jquery来完成这里我找到了教程
html
<textarea cols="30" rows="5" maxlength="10"></textarea>
jQuery
jQuery(function($) {
// ignore these keys
var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
// use keypress instead of keydown as that's the only
// place keystrokes could be canceled in Opera
var eventName = 'keypress';
// handle textareas with maxlength attribute
$('textarea[maxlength]')
// this is where the magic happens
.live(eventName, function(event) {
var self = $(this),
maxlength = self.attr('maxlength'),
code = $.data(this, 'keycode');
// check if maxlength has a value.
// The value must be greater than 0
if (maxlength && maxlength > 0) {
// continue with this keystroke if maxlength
// not reached or one of the ignored keys were pressed.
return ( self.val().length < maxlength
|| $.inArray(code, ignore) !== -1 );
}
})
// store keyCode from keydown event for later use
.live('keydown', function(event) {
$.data(this, 'keycode', event.keyCode || event.which);
});
});
于 2012-09-24T16:14:39.993 回答