本文主要是介绍textarea 动态限制字数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>关于文本框的字数限制功能</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var thresholdcolors=[['20%','darkred'], ['10%','red']] //[chars_left_in_pct, CSS color to apply to output]
var uncheckedkeycodes=/(8)|(13)|(16)|(17)|(18)/ //keycodes that are not checked, even when limit has been reached.
thresholdcolors.sort(function(a,b){return parseInt(a[0])-parseInt(b[0])}) //sort thresholdcolors by percentage, ascending
function setformfieldsize($fields, optsize, optoutputdiv){
var $=jQuery
$fields.each(function(i){
var $field=$(this)
$field.data('maxsize', optsize || parseInt($field.attr('data-maxsize'))) //max character limit
var statusdivid=optoutputdiv || $field.attr('data-output') //id of DIV to output status
$field.data('$statusdiv', $('#'+statusdivid).length==1? $('#'+statusdivid) : null)
$field.unbind('keypress.restrict').bind('keypress.restrict', function(e){
setformfieldsize.restrict($field, e)
})
$field.unbind('keyup.show').bind('keyup.show', function(e){
setformfieldsize.showlimit($field)
})
setformfieldsize.showlimit($field) //show status to start
})
}
setformfieldsize.restrict=function($field, e){
var keyunicode=e.charCode || e.keyCode
if (!uncheckedkeycodes.test(keyunicode)){
if ($field.val().length >= $field.data('maxsize')){ //if characters entered exceed allowed
if (e.preventDefault)
e.preventDefault()
return false
}
}
}
setformfieldsize.showlimit=function($field){
if ($field.val().length > $field.data('maxsize')){
var trimmedtext=$field.val().substring(0, $field.data('maxsize'))
$field.val(trimmedtext)
}
if ($field.data('$statusdiv')){
$field.data('$statusdiv').css('color', '').html($field.val().length+"<font color='red'>/"+$field.data('maxsize')+"</font>")
var pctremaining=($field.data('maxsize')-$field.val().length)/$field.data('maxsize')*100 //calculate chars remaining in terms of percentage
for (var i=0; i<thresholdcolors.length; i++){
if (pctremaining<=parseInt(thresholdcolors[i][0])){
$field.data('$statusdiv').css('color', thresholdcolors[i][1])
break
}
}
}
}
jQuery(document).ready(function($){ //fire on DOM ready
var $targetfields=$("input[data-maxsize], textarea[data-maxsize]") //get INPUTs and TEXTAREAs on page with "data-maxsize" attr defined
setformfieldsize($targetfields)
});
//以上代码可以封装起来,,,方便使用,,,,
</script>
</head>
<body>
<p>请输入<50个字符</p>
<textarea id="textarea" style="width:300px; height:150px" data-maxsize="50" data-output="sp" >
</textarea><span id='sp'></span><!--span可以去掉,根据需要而定 --!>
<p>请输入 (<6 字符)</p>
<input type="text" name="T1" size="15" data-maxsize="6" data-output='text1'><span id="text1"></span><!--span可以去掉,根据需要而定 --!>
</body>
</html>
这篇关于textarea 动态限制字数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!