本文主要和大家介绍JavaScript实现的仿新浪微博原生态输入字数即时检查功能,涉及javascript事件响应及字符串的遍历、转换、判断等相关操作技巧,需要的朋友可以参考下,希望能帮助到大家。
边在文本框输入字符边对输入的字数进行检查本来不难的,但是由于其中有些函数的使用方式大家容易混乱,很容易导致整个结果搞来搞去也没有搞出来,也容易出Bugs,注意这里不能再使用length函数了,因为这个东西英文算一个字符,汉字也算一个字符,不符合数据传递的形式。也不能用OnChange事件了,这事件要光标离开为文本框才会触发,必须改成更加即时的OnKeyUp。
一、基本目标
如下图,完成一个仿新浪微博的,不用任何插件,纯Javascript无JQuery的带字数统计的输入框,如果超出字数则给出相应的提示。
英文算半个字,中文才算1个字。

二、基本布局
没什么好说的。主要是提示文字给一个ID=test,字数统计的地方因为时时变更,因此也要给出一个ID=wordLength,之后脚本处的inputTest函数,又文本框的onkeyup事件触发,同时把自己此刻的值传递过去。同时注意到,字数统计的地方之所以与新浪微博的部分相似,就是因为新浪微博那里用了Georgia字体,这字体显示的数字比较独特。
1 2 3 4 5 6 7 8 9 10 11 | <!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>
<meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" />
<title>输入字数检查</title>
</head>
<body>
<p id= "test" ></p>
<span><input type= "text" onkeyup= "inputTest(this.value)" placeholder= "请在此输入" /></span><span id= "wordLength" style= "font-family:Georgia;" >0/10</span>
</body>
</html>
|
Copier après la connexion
三、核心脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <script>
function getStrLength(str){
var mylen=0;
for ( var i=0;i<str.length;i++){
if (str.charCodeAt(i)>0&&str.charCodeAt(i)<128){
mylen++;
} else {
mylen+=2;
}
}
return mylen;
}
function inputTest(value){
document.getElementById( "wordLength" ).innerHTML=parseInt(getStrLength(value)/2)+ "\/10" ;
if (parseInt(getStrLength(value))>20){
document.getElementById( "test" ).style.display= "block" ;
document.getElementById( "test" ).innerHTML= "太长,请修改至10字之内" ;
document.getElementById( "test" ).style.color= "#ff0000" ;
}
else {
document.getElementById( "test" ).innerHTML= "" ;
document.getElementById( "test" ).style.display= "none" ;
}
}
</script>
|
Copier après la connexion
相关推荐:
JavaScript实现选中文字提示新浪微博分享效果
JS中实现新浪微博分享效果的实例教程
ThinkPHP仿新浪微博项目实战视频教程_高清+源码
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!