根据字符数突出显示子文本

问题描述:

基本思想是突出显示输入中指定长度值后的字符,并显示通知消息。根据字符数突出显示子文本

这里,我们去:

<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

我不确定“突出显示”超过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,关于通知感谢您的回答!会尝试模拟该领域。谢谢 –

突出文本的某​​些部分并不是不可能的,因为您可以通过选择突出显示它。

检查了这一点: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

关于用户友好的你是对的,你的解决方案很有趣。谢谢你的回答 –