Chrome中getComputedStyle()无法枚举短横线命名CSS属性的解决方法
Chrome中getComputedStyle无法枚举CSS自定义属性的解决办法
问题说明
在Chrome浏览器中,通过window.getComputedStyle()获取根元素计算样式后,能通过getPropertyValue('--test')正常读取CSS自定义属性,但无法通过for...of枚举到这些以--开头的自定义属性。
原代码(存在兼容性问题)
JavaScript代码
let cs = window.getComputedStyle(document.documentElement); // 可以正常获取 console.log('cs', cs.getPropertyValue('--test')); // Chrome中无法枚举到自定义属性 for (let i of cs) { if (i.startsWith('--')) { console.log('for let', i); } }
CSS代码
:root { --test: #000; }
跨浏览器兼容解决方案
利用浏览器API差异,封装一个get_styles()函数,自动适配不同内核的浏览器:
- WebKit内核(如Chrome)使用
computedStyleMap()获取样式映射,该API支持枚举CSS自定义属性 - Gecko内核(如Firefox)则通过原有的
getComputedStyle()结合数组转换来枚举样式
优化后的代码
JavaScript代码
function get_styles() { if ('computedStyleMap' in document.documentElement) { // 适配WebKit内核浏览器(Chrome等) return document.documentElement.computedStyleMap(); } else { // 适配Gecko内核浏览器(Firefox等) let cs = window.getComputedStyle(document.documentElement); return [...cs].map((key) => [key, cs.getPropertyValue(key)]); } } let styles = get_styles(); for (let [key, val] of styles) { if (key.startsWith('--')) { console.log(key + ' ' + val); } }
CSS代码
:root { --test: #000; }
内容的提问来源于stack exchange,提问作者nett
相关产品推荐
相关产品推荐

