javascript javascript防止复制/粘贴超出textarea中的字符限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15573561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:13:27  来源:igfitidea点击:

javascript prevent copy/pasting beyond character limit in textarea

javascripttextarea

提问by Brian Phillips

I have the following code (pulled from this question) for setting a character limit on textareas.

我有以下代码(从这个问题中提取)用于在 textareas 上设置字符限制。

function maxLength(el) {    
    if (!("maxLength" in el)) {
        var max = el.attributes.maxLength.value;
        el.onkeypress = function () {
            if (this.value.length >= max) return false;
        };
    }
}

var maxtext = document.getElementsByClassName("maxtext");

for (var i = 0; i < maxtext.length; i++) {
    maxLength(maxtext[i]);
}

And an example of my html for textareas:

以及我的 textareas html 示例:

<textarea maxlength="150" class="maxtext"></textarea>

This all works just fine in Firefox and Chrome. In IE7+, it will stop me if I type up to the limit, but I'm then able to copy/paste text without restriction.

这一切在 Firefox 和 Chrome 中都可以正常工作。在 IE7+ 中,如果我输入到限制,它会阻止我,但我可以不受限制地复制/粘贴文本。

Any way to modify this script to prevent copy/pasting beyond the max character limit?

有什么方法可以修改此脚本以防止复制/粘贴超出最大字符数限制?

回答by Chase

Listen for the onpasteevent. Once the event fires, grab the text from the clipboardand manipulate it how you like.

监听onpaste事件。事件触发后,从剪贴板中抓取文本并按照您的喜好对其进行操作。

HTML

HTML

<textarea id="test" maxlength="10" class="maxtext"></textarea>

JAVASCRIPT

爪哇脚本

var test = document.getElementById("test");

test.onpaste = function(e){
    //do some IE browser checking for e
    var max = test.getAttribute("maxlength");
    e.clipboardData.getData('text/plain').slice(0, max);
};

EXAMPLE

例子

回答by Shuping

You could listen to the onchangeevent to check the content length, if exceeds the limit then subtract it.

您可以监听onchange事件以检查内容长度,如果超过限制则减去它。