html - 仅将样式应用于空输入/文本区域

标签 html css forms

我想知道是否可以只将样式应用于空文本区域。作为一个最小的例子,我想要一个评论框,它在用户点击它时展开(: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/

相关文章:

javascript - 使用 jquery 将另一个 div 悬停时移动 div

php - 数据在 MySQL 数据库中保存两次。不知道我做错了什么?

html - 使用 UIKit 的目录页面

jquery - 如何使我的移动汉堡菜单居中并防止我的菜单在单击菜单项时消失?

javascript - 在 Javascript 中获取要 POST 的表单

css - 强大的 WordPress 形式增加了三倍

html - 不同高度的 Bootstrap 网格行

jquery - 我想在标题右侧添加图片,同时将标题保持在页面中央

html - Bootstrap 3 行问题中的堆叠选项卡

html - 在 Div HTML 和 CSS 中垂直对齐 Img