如何在 CSS 中为="XYZ" 选择标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2599627/
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
How to select label for="XYZ" in CSS?
提问by Kyle
HTML:
HTML:
<label for="email">{t _your_email}:</label>
<label for="email">{t _your_email}:</label>
CSS:
CSS:
label {
display: block;
width: 156px;
cursor: pointer;
padding-right: 6px;
padding-bottom: 1px;
}
I wish to select the label based on the 'for' attribute to make layout changes.
我希望根据 'for' 属性选择标签以进行布局更改。
回答by T.J. Crowder
The selector would be label[for=email]
, so in CSS:
选择器是label[for=email]
,所以在 CSS 中:
label[for=email]
{
/* ...definitions here... */
}
...or in JavaScript using the DOM:
...或在 JavaScript 中使用 DOM:
var element = document.querySelector("label[for=email]");
...or in JavaScript using jQuery:
...或在 JavaScript 中使用 jQuery:
var element = $("label[for=email]");
It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.
这是一个属性选择器。请注意,某些浏览器(例如 IE < 8 的版本)可能不支持属性选择器,但最近的浏览器支持。遗憾的是,为了支持 IE6 和 IE7 等旧浏览器,您必须使用类(好吧,或其他结构方式)。
(I'm assuming that the template {t _your_email}
will fill in a field with id="email"
. If not, use a class instead.)
(我假设模板{t _your_email}
将用 填充一个字段id="email"
。如果没有,请改用类。)
Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier(for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:
请注意,如果您选择的属性值不符合CSS 标识符的规则(例如,如果其中包含空格或方括号,或以数字开头等),则需要在价值:
label[for="field[]"]
{
/* ...definitions here... */
}
They can be single or double quotes.
它们可以是单引号或双引号。
回答by Julio Cesar Brito Gomes
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
如果内容是变量,则需要用引号将其连接起来。它对我有用。像这样:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }