javascript 我无法访问文档中的CSS样式,styleSheets[...].cssRules[...]

v2g6jxz6  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(103)

我正尝试用javascript编写这个函数,它可以动态地重新排列特定父元素下的特定对象类。然而,我对我的一些变量有困难。

const styleSheet = Array.from(document.styleSheets[0].cssRules);
 //filter to create list that contains only "cartelle" class rulesets 
const myRules = styleSheet.filter(ruleset => ruleset.selectorText.includes("cartelle"))

 //iterate along each ruleset in the list
let cardSetLength = Object.keys(myRules).length;
console.log(cardSetLength);
for (let i = 0; i < cardSetLength; i++) {
  //obtain value of the following properties in given ruleset
  let newGridColumn = myRules[i][`grid-row-start`];
  let newGridRow = myRules[i][`grid-column-start`];
  console.log(newGridColumn);
  console.log(newGridRow);
}
.cartelle {
  grid-row-start: 42;
  grid-column-start: 69;
}

在这个示例中,newGridColumn和newGridRow的控制台日志都返回'undefined',我不知道为什么。cardSetlength的控制台日志返回了一个包含20个字典的列表,每个字典代表一个规则集,但是每个字典都是空的,我不确定这是与控制台日志中的某些显示约定有关,还是与我的错误有关。知道我哪里做错了吗

46scxncf

46scxncf1#

您应该从CSSRulestyle字段访问CSS属性值。

console.log(document.styleSheets[0].cssRules[0].backgroundColor); // undefined
console.log(document.styleSheets[0].cssRules[0].style.backgroundColor);
.class {
  background-color: blue;
}

你的代码应该看起来像这样:

for (const rule of myRules) {
    let newGridColumn = rule.style[`grid-row-start`];
    let newGridRow = rule.style[`grid-column-start`];
    // ...
}

请注意,在JavaScript中,CSS属性可以使用 Camel 大小写,而不是括号表示法。

相关问题