效果图
默认状态
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
textarea {
width: 350px;
height: 150px;
}
.zi {
color: red;
position: relative;
left: 100px;
top: -26px;
}
button {
display: inline-block;
background: cornflowerblue;
width: 70px;
height: 30px;
}
</style>
</head>
<body>
<textarea type="text" value="" name="" id="bigtext"></textarea>
<span id="stspan" style="font-family: Georgia;"></span>
<br>
<button id="but">发布</button>
<span id="bb" class="zi" style="display: block;"></span>
<ul></ul>
<script>
let text = document.getElementById('bigtext')
let sp = document.getElementById('stspan')
let zi = document.getElementById('bb')
let but = document.getElementById('but')
var ul = document.getElementsByTagName('ul')[0];
let onoff = false
text.oninput = () => {
let bigtext = text.value
//将value值转成数组
let text2 = bigtext.split("")
//获取留言框的里字数
let arr = text.value.length
//判断留言框是否有值,如果有值就开始计数
if (text.value == '') {
sp.innerHTML = ''
} else {
sp.innerHTML = '已输入' + arr + '字'
zi.innerHTML = ''
}
//判断留言框字数是否大于140
if (arr >= 140) {
let bigtext2 = bigtext.slice(0, -1)
text.value = bigtext2
zi.innerHTML = '留言字数只能140个字'
return
}
}
//点击按钮进行留言
but.onclick = () => {
let bigtext = text.value
if (!bigtext.trim()) {
alert('请输入内容')
return
}
//创造li标签
let li = document.createElement('li')
li.innerHTML = bigtext
//创造a标签
let a = document.createElement('a')
a.innerHTML = '删除'
a.href = 'javascript:;'
a.style.marginLeft = '10px'
a.style.fontSize = '14px'
//点击a标签删除a的父元素
a.onclick = function () {
ul.removeChild(this.parentNode);
}
//将a标签插入li里
li.appendChild(a)
//让最新的留言保持在第一条的位置
if (ul.childNodes[0]) {
ul.insertBefore(li, ul.childNodes[0]);
} else {
//将li插入ul标签
ul.appendChild(li);
}
text.value = ''
sp.innerHTML = ''
}
</script>
</body>
</html>