javascript防止复制/粘贴超出textarea中的字符数限制 [英] javascript prevent copy/pasting beyond character limit in textarea

查看:33
本文介绍了javascript防止复制/粘贴超出textarea中的字符数限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(从此问题中提取)来设置字符限制文本区域.

I have the following code (pulled from this question) for setting a character limit on 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]);
}

还有我的用于文本区域的html的示例:

And an example of my html for textareas:

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

这一切在Firefox和Chrome中都可以正常工作.在IE7 +中,如果我输入的字符数超出限制,它会阻止我,但是我可以不受限制地复制/粘贴文本.

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.

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

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

推荐答案

收听剪贴板中获取文本并进行操作你喜欢.

Listen for the onpaste event. Once the event fires, grab the text from the clipboard and manipulate it how you like.

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);
};

示例

这篇关于javascript防止复制/粘贴超出textarea中的字符数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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