您好,我正在尝试限制 contenteditable="true" div 中的文本:
var char = 500;
$("#counter").append("You have <strong>" + char + "</strong> chars left.");
$("#editor").keypress(function () {
if ($(this).text().length > char) {
$(this).text($(this).text().substr(1));
}
var rest = char - $(this).text().length;
$("#counter").html("You have <strong>" + rest + "</strong> chars left.");
if (rest <= 100) {
$("#counter").css("color", "#ff7777");
}
else {
$("#counter").css("color", "#111111");
}
});
不幸的是我面临以下问题:
- 当 div 默认包含任何文本时,剩余的字符数在任何插入或删除之前不会更新。
- 如果用户超过最大字符数,回车符将转到文本框的开头并删除第一个字符而不是最近插入的字符。
- 如果用户粘贴的文本长度超过 200 个字符,则不会被缩短。
请查找代码:http://jsfiddle.net/mmacin/A69tk/1/ http://jsfiddle.net/mmacin/A69tk/1/
这是我提供解决方案的尝试。它缺少一块拼图,我很快就会完成。
这里是fiddle http://jsfiddle.net/marsone/A69tk/3/
计数器现在可以按需要工作了。剩下的就是如果用户超出限制应该做什么。
如果您使用过 Twitter,您会发现他们不会删除多余的字符,而是用红色选择突出显示这些字符,以向用户表明这些字符不会成为推文的一部分。也许这样的替代方案会更好
这是我使用的 jQuery。
const limit = 200;
rem = limit - $('#editor').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#editor").on('input', function () {
var char = $('#editor').text().length;
rem = limit - char;
$("#counter").html("You have <strong>" + rem + "</strong> chars left.");
console.log(char)
console.log(rem);
if (char >= 100) {
$("#counter").css("color", "#ff7777");
}
else
$("#counter").css("color", "#111111");
if(char>200)
{
//add code to either remove extra chars or highlight them.
}
});
如果你看到我用过$("#editor").on('input', function ()
它将检查文本区域内的输入而不是按键,以便应该照顾用户在文本区域内复制粘贴文本的情况。我还改变了计数器的工作方式。我相信你自己能弄清楚其中的逻辑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)