我正在尝试创建具有可编辑div而不是textarea的消息编辑器。我正在为可编辑div中的字符计数苦苦挣扎。如何获得准确的字符数?
如果我使用$(“#eidtor”)。text(),则在键入时它不会计算换行
如果我使用$(“#eidtor”)。html(),则在键入时它会为我提供html内容。
我如何处理如果用户粘贴的文本长于最大长度。它为粘贴文本中的新行创建<div>...</div>
。
如果我根据文本执行子字符串,则其新的换行符将被删除。
我不是在寻找跨浏览器支持解决方案。它应该在谷歌浏览器中工作。任何帮助,建议或指南将不胜感激。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var maxLen = 200;
$(document).ready(function () {
$("#eidtor").on("keydown", function (e) {handleKeydown(e);});
$("#eidtor").on("keyup", function (e) { handleKeyup(e); });
$("#eidtor").on("paste", function (e) { handlePaste(e); });
$("#charCount").html(maxLen);
});
function handleKeydown(e) {
var currentLen = $("#eidtor").text().length;
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s)
(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 (valid && !e.ctrlKey) {
currentLen++;
if (currentLen > maxLen) {
e.preventDefault();
}
}
}
function handleKeyup(e) {
var currentLen = $("#eidtor").text().length;
$("#charCount").html(maxLen-currentLen);
}
function handlePaste(e) {
setTimeout(function (e) {
var currentLen = $("#eidtor").text().length;
if (currentLen > maxLen) {
var tempMessage = $("#eidtor").text().substring(0, maxLen);
$("#eidtor").empty();
$('#eidtor').html(tempMessage);
currentLen = maxLen;
}
$("#charCount").html(currentLen);
});
}
</script>
<style type="text/css" >
#eidtor {
background-color: #fff;
resize: none;
overflow: auto;
padding: 5px;
height: 10em;
width: 20em;
border-style: solid;
border-color: black;
display:inline-block;
}
</style>
</head>
<body>
<div id="container" style="margin-left:2em;">
<div id="eidtor" style=""
contenteditable="true"></div>
<br/>
Remaining Character(s) : <span id ="charCount"></span>
</div>
</body>
</html>
最佳答案
我碰巧检查了https://stackoverflow.com/editing-help上的html,发现它使用了<pre>
标记,然后mdn说了Whitespace inside this element is displayed as typed.
,因为该语句未提及换行符(尽管mdn上的示例包括换行符,的行为就像空格一样),我在控制台上的document.getElementById('foo').innerText.substr(7,1)==='\n'
的帮助页面上进行了测试,结果为true
(当我看到第7个字符是换行符时)。直到今天我才知道这个标签。干杯!
关于javascript - 可编辑div中的文本计数和子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37234812/