获取document.styleSheets.cssRules中CSS属性返回undefined的问题求助
问题
我尝试编写一个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,我不清楚原因;console.log(cardSetLength)显示存在20个规则集,但每个规则集在控制台中显示为空字典,不确定这是控制台显示惯例还是代码错误,请问我哪里出错了?
解答
核心错误点
- CSS规则属性访问方式错误:
myRules[i]是CSSStyleRule对象,不能直接通过键名grid-row-start读取属性值,必须通过对象的style属性来获取,比如使用驼峰式的style.gridRowStart,或者style.getPropertyValue('grid-row-start')。 - 规则集长度统计冗余:
myRules本身是数组,直接用myRules.length就能获取长度,没必要用Object.keys(myRules).length,虽然结果一致,但属于多余操作。 - 控制台显示空字典的原因:这是浏览器控制台的默认展示逻辑,
CSSStyleRule对象不会直接展开显示所有属性,你需要手动展开对象查看style属性,或者直接打印myRules[i].style才能看到具体的样式键值对。
修正后的代码
const styleSheet = Array.from(document.styleSheets[0].cssRules); // 筛选包含"cartelle"的规则集,加可选链避免无selectorText的规则报错 const myRules = styleSheet.filter(ruleset => ruleset.selectorText?.includes("cartelle")); // 直接用数组length获取规则数量 const cardSetLength = myRules.length; console.log(cardSetLength); for (let i = 0; i < cardSetLength; i++) { // 两种正确获取样式值的方式 const newGridRow = myRules[i].style.gridRowStart; const newGridColumn = myRules[i].style.getPropertyValue('grid-column-start'); console.log(newGridRow); console.log(newGridColumn); }
额外提示
如果需要获取元素实际渲染的计算样式(而非样式表中定义的原始值),不要读取样式表规则,应该用getComputedStyle(targetElement)来获取目标元素的最终样式。
内容的提问来源于stack exchange,提问作者fafottos
相关产品推荐
相关产品推荐

