【发布时间】:2016-03-25 10:11:20
【问题描述】:
我在 html 标头的 Style 标记中有 CSS。我想要的是通过 javascript 访问 Style 标签的所有类并检查它是否有font-weight:bold;最后,我想要一个带有font-weight:bold 的类数组,以便稍后在javascript 中为它们分配id 属性。
CSS
span {
white-space: pre-wrap;
}
.pt-Normal {
line-height: 107.9%;
margin-bottom: 8pt;
font-family: Ca**strong text**libri;
font-size: 20pt;
margin-top: 0;
margin-left: 0;
margin-right: 0;
}
.pt-DefaultParagraphFont-000000 {
font-family: Calibri;
font-size: 11pt;
font-style: normal;
font-weight: bold;
margin: 0;
padding: 0;
}
.pt-DefaultParagraphFont-000001 {
font-family: Calibri;
font-size: 20pt;
font-style: normal;
font-weight: bold;
margin: 0;
padding: 0;
}
.pt-Normal-000002 {
line-height: 107.9%;
margin-bottom: 8pt;
font-family: Calibri;
font-size: 11pt;
margin-top: 0;
margin-left: 0;
margin-right: 0;
}
.pt-DefaultParagraphFont-000003 {
color: #FF0000;
font-family: Calibri;
font-size: 11pt;
font-style: normal;
font-weight: bold;
margin: 0;
padding: 0;
}
JAVASCRIPT,我想从那里访问 CSS 类属性。
//this is just example of one class having fontWeight:bold, but i want to do this in a generic way.
function sec(){var s = document.getElementsByClassName("pt-DefaultParagraphFont-000001");
for (var z = 0; z <= s.length;z++){s[z].setAttribute("id",z.toString());}}
var sc = document.getElementsByTagName("STYLE").style;
if (sc.fontWeight == bold){
//here i want to get all the class which have class attribute fontWeight:bold
//later on i want to assign id attribute to those elements which have fontWeight:bold
}
【问题讨论】:
-
您可能想查看
document.styleSheets,而不是通过样式节点,但您会错过浏览器的默认设置,例如<strong>节点,所以也许您最好还是简单地循环通过所有元素并检查他们的getComputedStyle(el).fontWeight... -
样式描述文本不是 DOM 的结构化部分(它也不是 XML!),但是有一个用于特定目的的 CSSOM。查看developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets 了解更多信息!但是,如果您像我一样,那么您可能不需要它,而只需使用 jQuery 更改一些样式,例如 $('my selector').css('my-attribute', 'myValue');
-
为什么需要访问样式表?
-
无论
document.styleSheets还是document.style,任何人都可以提供js 代码。 @Kaiido @ZPiDER -
@Emma 我觉得你解决问题的方法是错误的。你已经解释了你想要什么。但我认为,如果您能花一些时间更新您的问题,说出您为什么想要这个或问题是什么,那会更好。我相信社区会有更好的想法。
标签: javascript html css stylesheet