我有一个使用多个样式标签的 HTML 文档。其中一种样式具有以下内容
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056,
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
document.styleSheets
允许我访问文档使用的全套样式表。从那里 - 一旦我获得了正确的样式表 - 我可以使用 cssRules
数组属性来访问每个包含的样式的 selectorText
属性。但是,我一直无法弄清楚如何找到“正确的”样式表。虽然我可以给样式表一个 id
,但它不会作为 document.styleSheets[n] 对象的属性出现。
我做了很多 DOM 操作,但主要是文档中的可视元素。如果有人能告诉我如何确定“正确的”样式表,我将不胜感激
任务的简单英文版本
一个。找到 style 元素 - 请记住还有其他元素 - id 为 pstyle
b.阅读其中定义的类名并执行任何操作
最佳答案
我不确定您是否想获得与 <style>
关联的样式表元素,或者如果你想从样式表中检索元素。
所以在这里你会得到两者:
// from the element
console.log(pstyle.sheet === document.styleSheets[2]);
// from the stylesheet
console.log(document.styleSheets[2].ownerNode === pstyle);
<style id='pstyle'>
</style>
请注意,在代码片段中它是 [2]
因为 stacksnippet 确实会注入(inject)样式表
现在要获取 cssRules 和 selectorText,您只需从选定的样式表中读取它:
var pstyle = document.getElementById('pstyle');
// from the element
console.log(pstyle.sheet.cssRules[0].selectorText);
// from the stylesheets
for(var sheet of document.styleSheets){
if(sheet.ownerNode === pstyle){
console.log(sheet.cssRules[0].selectorText);
}
}
<style id='pstyle'>
.p0010, .p0016, .p0022, .p0028, .p0032,
.p0034, .p0038, .p0042, .p0044, .p0046,
.p0048, .p0050, .p0052, .p0054, .p0056
{
max-width:100%;
background-size:100%;
background-image: url('sprites.png');
}
</style>
关于css - 在样式表中读取类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44761181/