HTML
<div id="box">
<textarea id="text" cols="30" rows="10"></textarea>
<button>发布</button>
</div>
CSS
*{
margin: 0;
padding: 0;
}
textarea{
resize: none;
}
a{
text-decoration: none;
color: red;
}
#box{
width: 300px;
margin: 20px auto;
}
li{
width: 250px;
background: #eee;
margin: 5px 0;
}
li>a{
float: right;
}
.msg{
width: 250px;
max-width: 250px;
height: auto;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
JS
var box = document.querySelector('#box')
var text = document.querySelector('#text');
var btn = document.querySelector('button');
var ul = document.createElement('ul'); //动态生成ul标签
var cc = 0; //统计发了多少条留言
box.appendChild(ul)
btn.onclick = function(){
if(text.value.trim() === ''){ //去掉左右两边空格判断是否为空
alert('输入内容不能为空');
return;
}else{
cc++;
var li = document.createElement('li')
var a = document.createElement('a')
a.href = 'javascript:;';
a.innerHTML = '删除';
li.innerHTML = text.value;
li.className = 'msg'; //添加类,超出部分变成省略号
li.appendChild(a)
a.onclick = function(){
ul.removeChild(this.parentNode)
}
var lis = document.getElementsByTagName("li");
if(cc === 1){
ul.appendChild(li) //如果是第一次发布留言用appendChild
}else{
ul.insertBefore(li,lis[0]) //最新的留言总在第一条显示
}
text.value = '' //发布成功后文本框内容清空
//留言数超过5条,删除最后一条留言
if(lis.length>5){
ul.removeChild(lis[lis.length-1])
}
}
}
运行实例