JavaScript微博输入字数(完整)

Original 2019-03-28 15:42:41 237
abstract:<style type="text/css"> .wb{border: solid 10px pink; width: 600px;height: 170px;margin: 0 auto;padding: 15px;} .clear{clear: both
<style type="text/css">
.wb{border: solid 10px pink; width: 600px;height: 170px;margin: 0 auto;padding: 15px;}
.clear{clear: both;}
.wb .logo{float: left;}
.wb .tit{float: right;}
.wb #area{width: 600px;height: 100px;margin-top: 15px;}
.wb .box span{width: 40px;height: 32px; line-height: 32px; padding-left: 25px;}
.wb .box1{background: url(wbimg/an5.png) no-repeat left center;}
.wb .box2{background: url(wbimg/an4.png) no-repeat left center;}
.wb .box3{background: url(wbimg/an3.png) no-repeat left center;}
.wb .box4{background: url(wbimg/an2.png) no-repeat left center;}
.wb .box5{background: url(wbimg/an1.png) no-repeat left center;}
.wb .box6{padding-left: 120px!important;}
.wb #bt{border: none;width: 80px;height: 32px;line-height: 32px;background-color: orange;color: #fff;border-radius: 5px;float: right;cursor: pointer;font-weight: bold;}
</style>
<div class="wb">
	<img src="wbimg/12.png" class="logo">
	<div class="tit">还可以输入 <span id="number">140</span> 字</div>
	<div class="clear"></div>
	<textarea name="area" id="area"></textarea>
	<div class="box">
		<span class="box1">表情</span>
		<span class="box2">图片</span>
		<span class="box3">视频</span>
		<span class="box4">话题</span>
		<span class="box5">长微博</span>
		<span class="box6">公开</span>
		<input type="button" name="bt" value="发布" id="bt">
	</div>
</div>
<script type="text/javascript">
	var area,number,m; 
	window.onload = function(){
		area = document.getElementById('area'); //area是获取输入框的内容
		number = document.getElementById('number');  //number是获取还可以输入多少字的数字内容
		bt = document.getElementById('bt');
		area.onkeyup = function (){
			m = 140-area.value.length;  //m是总字数-当前输入字数,即还可以输入的多少字数
			if(m<0){   //如果剩余输入字数少于0,即负值,就变换个颜色
				number.style.color='red';
			}else{
				number.style.color='#666';
			}
			number.innerHTML=m;   // 把剩余输入字数赋值给number元素
		}
		bt.onclick = function(){
			if(m == 140){
				alert("你还没有输入");
			}else if(m<0){
				alert("您输入字数过多,可输入最多140字");
			}else{
				alert("发布成功!");
			}
		}
	}

</script>

总结:用规定的字数(140)减去获取(onkeyup)输入框的字数,得到还可输入的字数(变量m),最后赋值给获取的number。在对number做完善的判断处理。和提交的判断处理。

注意下:getElementById("id名") 获取指定元素

getElementsByClassName("class名") 获取class元素

getElementsByTagName("标签名") 获取class元素

因为id是唯一的,所以Element后面不加s,其他获取的均为集合,加s

Correcting teacher:天蓬老师Correction time:2019-03-28 17:19:03
Teacher's summary:这和刚才应该是同一个作业的二个部分, 其实现在很多的UI组件,都自带有统计字数的文本域控件的, 不过, 了解字数的统计原理, 还是有必要的

Release Notes

Popular Entries