基本思想是在输入中指定长度值后突出显示字符,并显示一条通知消息。

开始了:

<div id="test_box">
   <input type="text" id="text_text">
</div>

CSS:
 #notice {
    width: 140px;
    height: 40px;
    background-color: black;

    }
 #test_box {
       width: 400px;
       height: 400px;

 }

和jQuery代码:
$(document).ready(function() {
        var length = $('#text_text').val().length;
        var char_limit = 5;
        $('#text_text').bind('keyup', function() {
            new_length = $('#text_text').val().length;
            if (new_length > char_limit) {
              $('#text_text').css('color','red');
                $('#test_box').append('<div id="notice"> There are limit of character for home page title of this field </div>'); // wrong too much divs :/

            } else {
               $('#text_text').css('color', 'black');
               $('#notice').hide(); //wrong
            }
        });
 });

目前超过了char_limit之后突出显示的字符,我需要的是仅突出显示那些在char_limit之后使用的字符。而且还请注意,如果我输入字符,每次都会添加块,我想我应该手动创建该div,或者不手动创建,并在超过char_limit时以某种方式出现。

最佳答案

我不确定“突出显示”超出char_limit的字符是什么意思。如果要将样式应用于部分输入文本,则不可能:样式将应用于整个输入。您可以尝试使用跨度和一些JavaScript来模拟输入字段,以监听键盘事件。这在this answer to a similar question as yours中进行了解释。

实际上,对于该通知,您不应该每次都添加它。它应该在HTML中,带有CSS“display:none”,并在适当时显示和隐藏。

<div id="test_box">
    <input type="text" id="text_text">
    <div id="notice"> There are limit of character for home page title of this field </div>
</div>

-
#notice {
    width: 140px;
    height: 40px;
    background-color: black;
    display:none;
}

-
$(document).ready(function() {
    var length = $('#text_text').val().length;
    var char_limit = 5;
    $('#text_text').bind('keyup', function() {
        new_length = $('#text_text').val().length;
        if (new_length > char_limit) {
          $('#text_text').css('color','red');
            $('#notice').show();

        } else {
           $('#text_text').css('color', 'black');
           $('#notice').hide();
        }
    });

});

那个代码的Here is a JSFiddle

09-30 16:11
查看更多