我想设置div的最大文本长度。
我在这里有此HTML代码:
<div contentEditable=true data-ph="Subject of this message" maxlength = "10" id = "discussionsubject">
</div>
在其中我表现DIV
得像textarea
。现在,我尝试将其设置为“maxlength
通过”,10
但它不起作用。
还尝试了在其他SO问题中发现的一些代码,这些代码对我来说似乎无法正常工作:
var myDiv = $('#discussionsubject');
myDiv.text(myDiv.text().substring(0,10));
还尝试了以下代码,但仍然无法正常工作:
$("div#discussionsubject).text(function(index, currentText) {
return currentText.substr(0, 10);
});
请帮助
我希望以下代码可以为您提供帮助:
//Maximum number of characters
var max = 10;
$('#editable_div').keydown(function(e) {
var keycode = e.keyCode;
//List of keycodes of printable characters from:
var printable =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
if (printable) {
return $(this).text().length <= max;
}
});
更新
对于管理复制和粘贴操作,您需要管理以下事件处理程序:
document.getElementById("discussionsubject").addEventListener("input", function () {
alert("input event fired");
}, false);
现在,将第一个代码块中的逻辑合并到更新的事件处理程序中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句