css - 如果存在文本,则保持焦点样式

标签 css css-selectors

我有一个输入框。我在正常状态和焦点下自定义它。

我的问题是,如果输入框中存在文本,如何保持焦点 CSS 样式?

.par input[type=sample]{
    width:75px;
    background-color: #000;
}
.par input[type=sample]:focus{
    width:50px;
    background-color: #FF0;
}

最佳答案

没有纯 CSS 选择器可以根据文本框的内容直接选择文本框并设置其样式。但如果该字段是必填字段(即,您可以添加 required 属性),则可以使用 :valid 伪选择器来识别文本框是否有任何是否在其中输入文本,并根据它应用所需的样式。

input[type=text] {
  width: 75px;
  background-color: #000;
}
input[type=text]:focus,
input[type=text]:valid {
  width: 50px;
  background-color: #FF0;
}
<input type="text" required />
<input type="text" required />

关于css - 如果存在文本,则保持焦点样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36176503/

相关文章:

javascript - 从多个表单中选择的下拉列表

html - 搜索栏比网站的其余部分短?

html - ID 属性选择器 ^ 不起作用

css - 第一个元素内联 block CSS 选择器

jquery - 用于类/id 选择的 jQuery 轻量级替代方案

css - 有异常的交替行 > 继承背景颜色

ios - 如何有选择地向 UIWebView 添加样式表?

HTML/CSS hack 允许 overflow-x : auto & overflow-y: visible?

android - 如何为所有元素设置相同的选择器?

python - find 与 select_one 在 python 网页抓取中给我不同的结果