Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 模拟HTML输入的最佳方法是什么;“最大长度”;HTML文本区域上的属性?_Javascript_Html_Textarea - Fatal编程技术网

Javascript 模拟HTML输入的最佳方法是什么;“最大长度”;HTML文本区域上的属性?

Javascript 模拟HTML输入的最佳方法是什么;“最大长度”;HTML文本区域上的属性?,javascript,html,textarea,Javascript,Html,Textarea,HTML文本输入有一个名为“maxlength”的属性,由浏览器实现,如果设置该属性,将阻止用户输入一定数量的字符 $(document).ready(function () { $('textarea').on('keyup', function () { // Store the maxlength and value of the field. if (!maxlength) { var maxlength = $(this).attr('maxleng

HTML文本输入有一个名为“maxlength”的属性,由浏览器实现,如果设置该属性,将阻止用户输入一定数量的字符

$(document).ready(function () {


$('textarea').on('keyup', function () {
    // Store the maxlength and value of the field.
    if (!maxlength) {
        var maxlength = $(this).attr('maxlength');
    }
    var val = $(this).val();
    var vallength = val.length;

    // alert
    if (vallength >= maxlength) {


        alert('Please limit your response to ' + maxlength + ' characters');
        $(this).blur();
    }


    // Trim the field if it has content over the maxlength.
    if (vallength > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
        delete maxlength;
    });
});
另一方面,HTML textarea元素没有此属性。我的目标是在HTML文本区域上模拟maxlength的行为。要求:

  • 至少,显示(CSS更改)用户键入的字符过多
  • 理想情况下,阻止用户输入更多字符,就像HTML输入一样
可以理解,服务器端验证应该再次检查长度。这里我只关注客户端部分


我的问题是:在HTML文本区域上模拟maxlength最干净的客户端方式是什么?理想情况下,请指向您使用过的一段经过验证的开源JavaScript。

查看此网站上的评论,并进行倒计时。我以前也这样做过,而且简单有效。StackOverflow也很好地利用了颜色

也许您没有足够的代表来查看评论框

当你打字时,它会倒计时。接近阈值时,颜色从黄色变为红色。所有这些都使用JavaScript,我假设textarea的keyup事件

编辑:用jQuery完成它怎么样

<script language="javascript" type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready( function () {
        setMaxLength();
        $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } )
    });

    function setMaxLength() {
        $("textarea.checkMax").each(function(i){
            intMax = $(this).attr("maxlength");
            $(this).after("<div><span id='"+this.id+"Counter'>"+intMax+"</span> remaining</div>");
        });
    }

    function checkMaxLength(strID){
        intCount = $("#"+strID).val().length;
        intMax = $("#"+strID).attr("maxlength");
        strID = "#"+strID+"Counter";
        $(strID).text(parseInt(intMax) - parseInt(intCount));
        if (intCount < (intMax * .8)) {$(strID).css("color", "#006600"); } //Good
        if (intCount > (intMax * .8)) { $(strID).css("color", "#FF9933"); } //Warning at 80%
        if (intCount > (intMax)) { $(strID).text(0).css("color", "#990000"); } //Over
    }
</script>

$(文档).ready(函数(){
setMaxLength();
$(“textarea.checkMax”).bind(“单击鼠标悬停键更改”,函数(){checkMaxLength(this.id);})
});
函数setMaxLength(){
$(“textarea.checkMax”)。每个(函数(i){
intMax=$(this.attr(“maxlength”);
$(此)。在(“+intMax+”剩余“)之后;
});
}
函数checkMaxLength(strID){
intCount=$(“#”+strID).val().length;
intMax=$(“#”+strID).attr(“maxlength”);
strID=“#”+strID+“计数器”;
$(strID).text(parseInt(intMax)-parseInt(intCount));
如果(intCount<(intMax*.8)){$(strID).css(“color”,“#006600”);}//很好
如果(intCount>(intMax*.8)){$(strID).css(“color”,“#FF9933”)}//警告为80%
如果(intCount>(intMax)){$(strID).text(0).css(“color”,“#990000”);}//Over
}
HTML是

<textarea id="text" maxlength="250" class="checkMax"></textarea>

以下是对我来说可以正常工作的JavaScript代码:

onBlur="if (this.value.length > 500) { alert('The notes field only allows 500 characters. You have ' + this.value.length + ' characters.'); this.focus(); return false; }"

我认为以下是“干净”的。在Javascript中创建一个事件处理程序,将keydown事件和textarea字段作为输入。检查此处理程序中字段中文本的长度,如果达到maxlength,则返回false。(当然,在返回之前进行任何css样式切换)。否则返回true。文本区域应该是这样的

<textarea onkeydown="return checkMaxLength(event, this, 1000);"></textarea>

脚本可在他的网站上找到。没什么特别的,只是简单的老JavaScript

您可以轻松地将此作为起点,并进行更改以适应您的CSS“通知”需求

请注意,作者说:“我的脚本的目的不是强制执行最大长度,尽管可以很容易地更改它。但是,我决定限制我的脚本,当用户超过最大字符数时,礼貌地提醒用户。”

更新: 由于所附文章中的linkrot,以下是该链接上曾经存在的代码:

HTML:


JS:

函数setMaxLength(){
var x=document.getElementsByTagName('textarea');
var counter=document.createElement('div');
counter.className='counter';
对于(变量i=0;i最大长度)
this.relatedElement.className='TooMome';
其他的
this.relatedElement.className='';
this.relatedElement.firstChild.nodeValue=当前长度;
//不是innerHTML
}

只需调用
setMaxLength()加载时的函数。

使用JavaScript框架(,等等),以便获得跨浏览器事件支持。在
keyup
上写一行,以防止用户输入maxlength

注意:您还必须检查服务器端的长度。

我发现了一个很好的脚本,在输入字符串的长度超过MaxLen参数后,该脚本可以阻止用户输入更多文本,它有一个不可否认的好处,那就是基本上不让用户看到

我对该脚本的问题是,它还阻止了导航键(箭头、主页、结束)以及退格和删除,所以我稍微修改了它,否则用户无法删除他输入的文本,如果他达到MaxLen设置的限制(这可能有点滑稽:p)

Javascript:

function imposeMaxLength(Event, Object, MaxLen)
{
        return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
函数imposeMaxLength(事件、对象、最大值)
{

返回(Object.value.length=35&&Event.keyCode我想我可以试一试,这只是做同样事情的另一种方式。我喜欢这种方式,因为你可以用一些代码来包装它,检查你是否在IE中运行,因为maxlength在webkit和gecko浏览器中的文本区域工作。这取决于textar上设置的maxlength属性ea元素。这也是因为默认情况下,它实际上与maxlength属性在浏览器中的工作方式相同,从而防止用户添加超过指定字符的字符

$(document).ready(function () {


$('textarea').on('keyup', function () {
    // Store the maxlength and value of the field.
    if (!maxlength) {
        var maxlength = $(this).attr('maxlength');
    }
    var val = $(this).val();
    var vallength = val.length;

    // alert
    if (vallength >= maxlength) {


        alert('Please limit your response to ' + maxlength + ' characters');
        $(this).blur();
    }


    // Trim the field if it has content over the maxlength.
    if (vallength > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
        delete maxlength;
    });
});

这里有一个我使用的jQuery插件,名为“Simply Countable”,它允许您向文本区域添加计数器。其中一个功能是,它允许您设置字段中允许的最大字符数,并强制执行,以便用户不能超过该限制

下面是GitHub页面,用于简单可数:

你会像这样使用它

$('#my_textarea').simplyCountable({
    counter: '#counter',
    maxCount: 140,
    strictMax: true
});

有没有可能再详细说明一下如何克服粘贴?据我所知,当用户右键单击粘贴文本时,onkeypress不会启动。它工作正常。但正如您所提到的,用户可以通过粘贴文本来解决问题。使用“onchange”可以克服吗?您能解释一下吗?@dev我很抱歉,我不记得了,这很神秘我当时在想什么,但是
$(document).ready(function () {


$('textarea').on('keyup', function () {
    // Store the maxlength and value of the field.
    if (!maxlength) {
        var maxlength = $(this).attr('maxlength');
    }
    var val = $(this).val();
    var vallength = val.length;

    // alert
    if (vallength >= maxlength) {


        alert('Please limit your response to ' + maxlength + ' characters');
        $(this).blur();
    }


    // Trim the field if it has content over the maxlength.
    if (vallength > maxlength) {
        $(this).val(val.slice(0, maxlength));
    }
});

//remove maxlength on blur so that we can reset it later.
$('textarea').on('blur', function () {
        delete maxlength;
    });
});
$('#my_textarea').simplyCountable({
    counter: '#counter',
    maxCount: 140,
    strictMax: true
});