2012-10-18 1169 views
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時以某種方式顯示它。

+0

你可以使用文本框的mexlength屬性嗎? ''這將迫使這個問題不需要腳本。 – jwatts1980

+0

我不能這樣做,因爲我的網站用戶可以添加一些內容,每個內容都有標題,但在主頁上我需要顯示修剪標題和限制是5個atm,但這只是示例(限制將在稍後設置) ,所以我想讓用戶理解,如果他們在主頁上宣傳這個標題將會被修剪。 –

+0

如果你不介意使用jQuery插件:[jQuery Caret Plugin](http://www.jquery-plugin.buss.hk/my-plugins/jquery-caret-plugin),可以通過指定開始在「文本輸入框」(輸入類型=「文本」)或「文本區域」(文本區域)中選擇的位置,結束位置或長度 – RASG

回答

0

我不確定「突出顯示」超過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與該代碼。

+0

是的,我想將樣式應用於輸入的一部分,不知道這是什麼不可能作爲js,關於通知感謝您的回答!會嘗試模擬該領域。謝謝 –

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的問題。但是,我不覺得這個解決方案非常用戶友好。您可以嘗試將焦點移到輸入字段之外,但仍然不完全令人滿意。

+0

關於用戶友好的你是對的,你的解決方案很有趣。謝謝你的回答 –