contenteditable =“ true” div字符数限制 [英] contenteditable="true" div character limit

查看:197
本文介绍了contenteditable =“ true” div字符数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试限制contenteditable = true div中的文本:

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:


  1. 默认情况下,当div包含任何文本时,剩余的字符数直到进行任何插入或删除时才会更新。

  2. 如果用户超出了最大字符数字符,则转至文本框的开头,并删除第一个字符,而不是最近插入的字符。

  3. 如果用户粘贴的文本长度超过200个字符,则不会

请找到代码:
http://jsfiddle.net/mmacin/A69tk/1/

推荐答案

我尽力提供解决方案。它有一个难题,我很快就会完成。

Here is my go at providing a solution. It has one piece of the puzzle missing which i will complete soon.

这里是小提琴

计数器现在可以正常工作了。剩下的就是,如果用户超出限制,应该怎么做。

The counters work as desired now . What remains is if the user exceeds the limit what should be done.

如果您使用了twitter,您将看到它们不去除多余的字符,而是用红色选择高亮显示这些字符,以向用户显示这些字符不会可能是这样的替代方法会更好。

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

这是我使用的jQuery。

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.
    }

});

如果您看到我使用过 $(#editor)。on ('input',function(),它将检查文本区域内的输入内容,而不是按键操作,这样就可以照顾用户在文本区域内复制粘贴文本。此外,我还更改了计数器起作用。我确定您可以自己弄清楚逻辑。

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.

这篇关于contenteditable =“ true” div字符数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆