CSS 将样式应用于空输入 ([value=''])
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4717299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS apply style to empty inputs ([value=''])
提问by Ibolit
I would like to apply a special style to all inputs in my form that are required and empty at that.
我想对表单中所有必需且空的输入应用特殊样式。
It does work when i write in my css
当我在我的 css 中编写时它确实有效
input[required='required'] {
bla-bla-bla;
}
but it doesn't work, when i write
但它不起作用,当我写
input[value=''] {
bla-bla-bla;
}
I know i can do that using jQuery, but i would like to do that in pure css, if it is possible.
我知道我可以使用 jQuery 做到这一点,但如果可能的话,我想在纯 css 中做到这一点。
Can that be done?
可以做到吗?
Thank you in advance,
Timofey.
提前谢谢你,
蒂莫菲。
采纳答案by Yuji 'Tomita' Tomita
Searched css style empty inputsand found the following:
搜索css样式空输入,发现以下内容:
Matching an empty input box using CSS
You need to use JavaScript.
您需要使用 JavaScript。
To use the CSS style, you would have to type in the attribute: value=''
in your HTML, but then the CSS would match regardless of if the value changes mid-session.
要使用 CSS 样式,您必须value=''
在 HTML中输入属性:,但是无论值在会话期间是否更改,CSS 都会匹配。
回答by Falco
You can use the Pseudo-Selecot :invalidfor this - it will match an input only when the browser-validation fails for the element. If you set the element requiredit will be invalid as long as it is empty.
您可以为此使用 Pseudo-Selecot :invalid- 只有当元素的浏览器验证失败时,它才会匹配输入。如果设置了required元素,只要它是空的,它就会无效。
And all moder browsers support this CSS-class: Browser Compatibility
所有现代浏览器都支持这个 CSS 类:浏览器兼容性
input:invalid {
border-color: red;
}
<input type="text" required>
回答by TommyZG
If you don't have to support older IE versions, you can set the placeholder
attribute on your input to something (can be whitespace, but must be something) and use :placeholder-shown
to target that input.
如果您不必支持较旧的 IE 版本,您可以将placeholder
输入的属性设置为某物(可以是空格,但必须是某物)并用于:placeholder-shown
定位该输入。
<input type="text" class="custom-input" placeholder=" ">
.custom-input:placeholder-shown {
/* Your rules */
}