Html 通过 CSS 为元素分配类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8008110/
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
Assigning classes to elements through CSS
提问by
I'd like to tell the browser to assign certain CSS classes to elements matching a particular selector. Can I do it with pure CSS and if yes, how?
我想告诉浏览器将某些 CSS 类分配给与特定选择器匹配的元素。我可以用纯 CSS 来做,如果是,怎么做?
Example: I want all the h5
elements inside a div with id sidebar
to have the class ui-corners-all
示例:我希望h5
带有 id 的 div 中的所有元素sidebar
都具有该类ui-corners-all
采纳答案by ComFreek
No, that isn't possible with pure CSS.
不,这在纯 CSS 中是不可能的。
Only with JavaScript:
仅使用 JavaScript:
// jQuery
$("h5").addClass("ui-corners-all");
// Pure JavaScript
var elements = document.getElementsByTagName("h5");
for (var i=0; i<elements.length; i++)
{
var el = elements[i];
el.setAttribute( "class", el.getAttribute("class") + " ui-corners-all" );
}
回答by Curt
There is no way to assign this value to those elements in pure CSS.
无法在纯 CSS 中将此值分配给这些元素。
You would need to do:
您需要执行以下操作:
#sidebar h5
{
}
Then copy all styles from ui-corners-all
class into this.
然后将ui-corners-all
类中的所有样式复制到此。
Or alternatively, change your ui-corners-all
CSS to:
或者,将您的ui-corners-all
CSS更改为:
.ui-corners-all, #sidebar h5
{
}