问题
Hi I am trying to limit text in 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");
}
});
unfortunately I am facing following problems:
- When div contain any text by default, the number of chars left is not being updated until any insertion or deletion.
- If the user exceeds the maximum number of chars, the carriage goes to the beginning of the text box and deletes the first char instead of the recently inserted one.
- If user pastes a text longer than 200 chars, it won't be shortened.
Please find the code: http://jsfiddle.net/mmacin/A69tk/1/
回答1:
Here is my go at providing a solution. It has one piece of the puzzle missing which i will complete soon.
Here is the fiddle
The counters work as desired now . What remains is if the user exceeds the limit what should be done.
If you have used twitter, you will see that they do not strip the extra chars but higlight those chars with a red selection to show the user that those chars won't be part of the tweet.Perhaps such an alternative would be better
Here is the jQuery that i used.
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.
}
});
If you see I have used $("#editor").on('input', function ()
which will check for input's inside the textarea rather than key-press so that should take care of the user copy pasting text inside the textarea. Also I have changed the way the counters work. I'm sure you can figure out the logic yourself.
来源:https://stackoverflow.com/questions/18735061/contenteditable-true-div-character-limit