【发布时间】:2012-10-18 15:26:29
【问题描述】:
基本思路是高亮输入中指定长度值后的字符,同时显示提示信息。
我们开始吧:
<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 时以某种方式显示它。
【问题讨论】:
-
你可以只使用文本框的
mexlength属性吗?<input type="text" maxlength="5" value="" id="text_text" />这将在不需要脚本的情况下强制解决问题。 -
我不能那样做,因为我的网站用户可以添加一些内容并且每个内容都有标题,但是在主页上我需要显示修剪过的标题并且限制是 5 atm,但这只是示例(限制将在稍后设置),所以我想让用户了解如果他们在主页上宣传这个标题将被修剪。
-
如果你不介意使用jquery插件:jQuery Caret Plugin,可以
highlight text by specifying starting position, ending position or length of selection in a "text input box" (input type="text") or "text area" (textarea)
标签: javascript jquery