我想知道是否可以只将样式应用于空文本区域。作为一个最小的例子,我想要一个评论框,它在用户点击它时展开(:focus
),但在用户输入文本时保持展开状态,但在框为空时重新折叠.
我已经尝试过 :empty
,但这对输入/文本区域(仅 DOM 元素)不起作用。
#comments {
width: 150px;
height: 30px;
font-family: sans-serif;
border-radius: 5px;
outline:none;
-webkit-transition: all 1s;
-moz-transition: all 1s;
transition: all 1s;
}
#comments:not(:empty),
#comments:focus {
width: 250px;
height:100px;
border-radius: 10px;
}
<textarea type="text" id="comments" placeholder="Place a comment"></textarea>
有什么方法可以让用户在其中输入内容时保持输入较大?
最佳答案
据我所知,:empty 仍然是一个工作草案,可能不受您使用的特定浏览器的支持。
一种快速的 JavaScript 解决方案是根据文本区域是否具有值来添加/删除 HTML 类。
.empty{/*styles go here*/}
还有你的 JavaScript:
textareaElement.addEventListener('input',function(){
if(this.value && this.classList.contains("empty")) this.classList.remove("empty");
else this.classList.add("empty");
},false);
关于 Element.classList 的更多信息可以在 MDN 上找到.
关于html - 仅将样式应用于空输入/文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27590364/