3

基本的な考え方は、入力で指定された長さの値の後の文字を強調表示し、通知メッセージも表示することです。

どうぞ:

<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を超えたときに何らかの形で表示する必要があると思います。

4

2 に答える 2

2

テキストの一部を選択して強調表示することは不可能ではありません。

これをチェックしてください:http://jsfiddle.net/9BrpD/3/

$(document).ready(function(){
    var input = $('#text_text');
    var warning = $('#warning');
    input.on('keyup', function(){
       var val = $(this).val();
        if ( val.length > 3 ) {
            warning.html('hello').css('display', 'block');
            l = val.length
            var input = document.getElementById("text_text");
            input.setSelectionRange(l-3, l);
            input.focus();
        }
        else {
             warning.css('display', 'none');
        }
    });   

});​

また、繰り返しの div で発生した問題も解決します。ただし、このソリューションはあまりユーザーフレンドリーではありません。フォーカスを入力フィールドの外に移動しようとすることもできますが、それでも完全に満足できるものではありません。

于 2012-10-18T16:01:26.123 に答える
0

char_limit を超える文字を「強調表示」することの意味がわかりません。入力テキストの一部にスタイルを適用したい場合、それは不可能です: スタイルは入力全体に適用されます。スパンといくつかの JavaScript を使用して入力フィールドをシミュレートし、キーボード イベントをリッスンすることができます。これは、あなたと同様の質問に対するこの回答で説明されています。

通知については、確かに、毎回追加する必要はありません。css "display:none" を使用して HTML に配置し、必要に応じて表示および非表示にする必要があります。

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

});

これがそのコードを含む JSFiddleです。

于 2012-10-18T15:49:04.947 に答える