JS修改样式表中grid-template-column属性不生效问题求助
问题原因与解决方案
问题出在CSS属性名的拼写错误:
你在JS中使用的grid-template-column是单数形式,但标准CSS属性名是**grid-template-columns(复数)**,JS无法识别错误的属性名,导致样式修改不生效。而background-color属性名正确,所以能正常生效。
修正后的代码
将错误的属性名改为复数形式即可,两种写法任选其一:
// create a reference to linked stylesheet const stylesheet = document.styleSheets[0]; const rules = stylesheet.cssRules || stylesheet.rules; // loop through the style sheet reference to find the classes to be modified and modify them for (let i = 0; i < rules.length; i++) { if (rules[i].selectorText === '.grid-container') { rules[i].style['background-color'] = 'yellow'; // 写法1:保留CSS原生属性名(复数) rules[i].style['grid-template-columns'] = 'auto auto auto'; // 写法2:使用JS驼峰式命名 // rules[i].style.gridTemplateColumns = 'auto auto auto'; break; } }
补充说明
JS操作DOM样式时,属性名有两种合法写法:
- 用方括号包裹完整CSS属性名,保留连字符,比如
style['grid-template-columns'] - 转换为驼峰式命名,去掉连字符并将后续首字母大写,比如
style.gridTemplateColumns
两种写法功能完全一致,可根据习惯选择。
内容的提问来源于stack exchange,提问作者Garth Vader
相关产品推荐
相关产品推荐

