我想设置 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);
现在将第一个代码块的逻辑合并到更新的事件处理程序中。
关于javascript - DIV 的最大长度,例如 Textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471737/