样例:
CSS代码:
* {margin: 0;padding: 0;
}ul{list-style: none;
}.w {width: 900px;margin: 0 auto;
}.controls textarea {width: 878px;height: 100px;resize: none;border-radius: 10px;outline: none;padding-left: 20px;padding-top: 10px;font-size: 18px;
}.controls {overflow: hidden;
}.controls div {float: right;
}.controls div span {color: #666;
}.controls div .useCount {color: red;
}.controls div button {width: 100px;outline: none;border: none;background: rgb(0, 132, 255);height: 30px;cursor: pointer;color: #fff;font: bold 14px '宋体';transition: all 0.5s;
}.controls div button:hover {background: rgb(0, 225, 255);
}.controls div button:disabled {background: rgba(0, 225, 255, 0.5);
}.contentList {margin-top: 50px;
}.contentList ul {height: 800px;
}.contentList li {/* display: none; */padding: 20px 0;border-bottom: 1px dashed #ccc;height: 60px;
}.contentList li a {margin-left: 800px;
}
HTML代码:
<!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><link rel="stylesheet" href="./css/weibo.css"><script src="../发布微博案例/jquery-3.7.1.min.js"></script>
</head><body><div class="w"><div class="controls"><img src="images/tip.png" alt=""><br><textarea placeholder="说点什么吧..." id="area" cols="30" rows="10" maxlength="200"></textarea><div><span class="useCount">0</span><span>/</span><span>200</span><button id="send">发布</button></div></div><div class="contentList"><ul id="list"></ul></div></div><script src="./index.js"></script>
</body></html>
js代码:
const user=[{usname:'未命名',imgSrc:'images/03.jpg'}]
let textarea=document.querySelector('textarea')
let useCount=document.querySelector('.useCount')
let btn=document.querySelector('#send')
let ul=document.querySelector('#list')
//检测输入字数:
textarea.addEventListener('input',function(){useCount.innerHTML=this.value.length
})
btn.addEventListener('click',function(){//输入不能为空if(textarea.value.trim()===''){ return alert('内容不能为空')}function getrandom(min,max){return Math.floor(Math.random()*(max-min+1))+min}let a=getrandom(0,user.length-1)// 新增留言 应写在点击事件内部// 创建一个小li 然后里面通过innerHTML追加数据let li=document.createElement('li')li.innerHTML=`<div class="info"><img src=${user[a].imgSrc}><span class="username">${user[a].usname}</span><button class="del">删除</button><div class="content">${textarea.value}</div><div class="send-time">${new Date().toLocaleString()}</div>`//删除let del = li.querySelector('.del');del.addEventListener('click', function () {ul.removeChild(li);});//ul.insertBefore(li, ul.children[0]);textarea.value = '';useCount.innerHTML = 0;})
//再按下回车同时发送
textarea.addEventListener('keyup',function(a){if(a.key === 'Enter'){btn.click()}
})