一、基本思路:
1.写好基本样式后,通过id或标签名获取到数字、文本框及按钮
2.声明一个变量n,通过length方法获取到当前文本框字数,n=总字数-文本框字数
3.用n的值进行判断,若n>0,文本颜色不变,并用innerHTML方法将数字改为当前n的值,反之则变红色。
4.用n的值判断是否可以发布,大于总字数,弹出框提示减少字数后发布,小于则发布,当n=总字数时说明没有内容,提示用户写内容,并获取文本框焦点
二、运行结果及代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>微博输入框</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body{
background-color: #6aafd8;
}
.con{
width: 580px;
height: 21px;
overflow: hidden;
}
.box{
width: 580px;
height: 140px;
padding: 15px 10px 10px;
background-color: #fff;
border-radius: 6px;
margin:50px auto;
overflow: hidden;
}
#font{
color:#1b7fb6;
font-size: 18px;
font-family: "WBswficon";
float: left;
line-height: 21px;
}
.right{
font-size: 14px;
line-height: 21px;
float:right;
color: #888;
}
#zi{
font-size: 16px;
font-weight: bold;
}
#text{
width: 568px;
height: 68px;
padding: 5px;
margin-top: 4px;
}
.icon{
width: 400px;
height: 24px;
padding-top: 10px;
color: #373737;
float: left;
}
.icon span{
font-size:12px;
line-height: 24px;
margin-right: 18px;
}
.func{
width: 160px;
height: 30px;
padding: 5px 0 0;
float: right;
font-size: 12px;
line-height: 30px;
color: #373737;
overflow: hidden;
}
.func span{
height: 30px;
margin-left:50px;
}
button{
width: 60px;
height: 30px;
border:none;
border-radius:3px;
background-color: #ffc09f;
color: #fff;
float: right;
padding: 0 10px;
}
.sp1,.sp2,.sp3,.sp4,.sp5,.sp6{
font-size: 12px;
line-height:24px;
cursor: pointer;
color: #373737;
}
#fa{
margin-right:5px;
font-size: 16px;
}
.sp #fa{
color:green;
}
</style>
<script>
window.onload=function() {
var text = document.getElementById('text');
var zi = document.getElementById('zi');
var but = document.getElementById('but');
text.onkeyup=function aa() {
var n = 140-text.value.length;
if(n<0){
zi.style.color = 'red';
}else{
zi.style.color = '#888';
}
zi.innerHTML = n;
}
but.onclick=function(){
var n = 140-text.value.length;
if (n==140) {
alert("请输入内容后发布");
text.focus();
}else if(n<0){
alert("减少字数后再发布哦");
text.focus();
}else{
alert("发布成功");
}
}
}
</script>
</head>
<body>
<div>
<div>
<span id="font">有什么新鲜事想告诉大家?</span>
<div>还可以输入<span id="zi">140</span>字</div>
</div>
<textarea id="text"></textarea>
<div>
<span><i id="fa" class="fa fa-frown-o"></i>表情</span>
<span><i id="fa" class="fa fa-image"></i>图片</span>
<span><i id="fa" class="fa fa-youtube-play"></i>视频</span>
<span><i id="fa" class="fa fa-paperclip"></i>话题</span>
<span><i id="fa" class="fa fa-file-text"></i>头条文章</span>
<span><i id="fa" class="fa fa-ellipsis-h"></i></span>
</div>
<div>
<span>公开</span>
<button id="but">发布</button>
</div>
</div>
</body>
</html>