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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:23:27  来源:igfitidea点击:

Assigning classes to elements through CSS

htmlcss

提问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 h5elements inside a div with id sidebarto 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-allclass into this.

然后将ui-corners-all类中的所有样式复制到此。

Or alternatively, change your ui-corners-allCSS to:

或者,将您的ui-corners-allCSS更改为:

.ui-corners-all, #sidebar h5
{    

}

回答by Leonard

No, you can't. You can however use Javascript (jQueryrecommended) to achieve this effect.

不,你不能。但是,您可以使用 Javascript(推荐使用jQuery)来实现此效果。