文本域输入字数计算与提示

Original 2019-04-13 21:06:35 271
abstract:<!DOCTYPE html> <html> <head> <meta charset="utf-8">  <title>输入字数</title> <style> *{margin: 0;padding: 0;} textarea{
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>输入字数</title>
	<style>
		*{margin: 0;padding: 0;}
		textarea{margin: 100px auto 0;display: block;background: #aefffe;}
		button{width: 80px;height: 30px;background:blue;border-radius: 3px;color:white;margin: 20px auto 0;display: block;}
		button:hover{cursor: pointer;}
		div div{width: 400px;margin:20px auto;}
	</style>
</head>
<body>
	<div id="txt">
	<textarea id="txtInput" cols="100" rows="10" onkeyup="txtChange()" placeholder="请输入文字"></textarea><br>
	<div><span>您已输入</span><span id="txtCount">0</span><span>个字符,还可以输入</span><span id="txtLeft">140</span><span>个字符</span></div>
	<button id="mysubmit" type="button" onclick="mysubmit()">提交</button>
	</div>	
</body>
<script>
	
	var txtCount = document.getElementById("txtCount");
	var txtInput = document.getElementById("txtInput");
	var txtLeft = document.getElementById("txtLeft");

	function txtChange(){
		txtCount.innerText=txtInput.value.length;
		txtLeft.innerText = 140-txtInput.value.length;
	}	

	function mysubmit(){
		if(txtLeft.innerText==140){
			alert("输入不能为空");
		}else if(txtLeft.innerText<0){
			alert("不能超过140字");
		}else{alert("提交成功")};
	}
	</script>
</html>
-------------------------
效果图
-------------------------

QQ截图20190413205807.png

思路:

1、两个span用于实时计数

2、js获取文本域的值的长度

3、onkeyup事件触发给span文本赋值上一步获取的文本长度

4、点击提交按钮时,对字数进行判断,字数为零或字数超过140时,弹出警告信息


Correcting teacher:天蓬老师Correction time:2019-04-13 21:55:24
Teacher's summary:你的变量与函数的命名非常的规范, 事件也运行的正确... 顺便说一下,微博早已取消字数限制了

Release Notes

Popular Entries