输入框对象.value.trim() !== "" // trim() 去除左右空格
trim() 方法: 去除左右空格
eg:
<body>
<div class="wrapper"><textarea id="tx" placeholder="评论" rows="2" maxlength="200"></textarea><button>发布</button>
</div>
<div class="wrapper"><span class="total">0/200字</span>
</div>
<div class="list"><div class="item" style="display: none"><div class="info"><p class="name">hhhhhh</p><p class="text">perfect</p><p class="time">2023/07/30</p></div></div>
</div><script>const tx = document.querySelector("#tx")const total = document.querySelector(".total")const item = document.querySelector(".item")const text = document.querySelector(".text")tx.addEventListener("focus", function () { // 获得焦点total.style.opacity = 1})tx.addEventListener("blur", function () { //失去焦点total.style.opacity = 0})tx.addEventListener("input", function () {// console.log(tx.value.length) // 输入框文本长度total.innerHTML = `${tx.value.length}/200字`})// 按下回车发布评论tx.addEventListener("keyup", function (e) {if (e.key === 'Enter') {// 判断用户输入是否为空// if (tx.value.trim() !== ""){ // trim() 去除左右空格// 也可以这样写 if (tx.value.trim()){// console.log("键盘按下了")item.style.display = "block"text.innerHTML = tx.valueconsole.log(tx.value.trim() === "")}// 按下回车,清空文本域tx.value = ""// 按下回车,把字符统计复原total.innerHTML="0/200字"}})
</script>
</body>