如何获取CSSStyleDeclaration支持的所有CSS属性(含简写属性)
获取浏览器支持的所有CSS属性(包含简写属性)
你用getComputedStyle结合索引获取属性的方法,确实只能拿到展开后的长属性,像margin、font这类简写属性不会出现在索引列表里——因为计算后的样式会自动把简写展开成具体的长属性,所以索引枚举不到它们,但直接通过键名访问又能拿到值。
要拿到包含简写属性的完整列表,可以试试这两种方法:
方法一:手动维护简写属性列表 + 兼容性校验
先整理一份常见的CSS简写属性,再用CSS.supports判断浏览器是否支持该属性,最后和长属性列表合并:
// 整理的常见CSS简写属性(可根据需求补充) const shorthandProps = [ 'margin', 'padding', 'border', 'border-width', 'border-style', 'border-color', 'border-radius', 'font', 'background', 'transition', 'animation', 'flex', 'grid', 'gap', 'place-content', 'place-items', 'place-self', 'outline', 'list-style', 'text-decoration', 'overflow' ]; const styles = getComputedStyle(document.body); // 获取所有长属性 const longhandProps = Array.from({ length: styles.length }, (_, i) => styles[i]); // 筛选浏览器支持的简写属性 const supportedShorthands = shorthandProps.filter(prop => { // 用CSS.supports判断属性是否被浏览器识别,同时排除已经在长属性里的项 return CSS.supports(prop, 'initial') && !longhandProps.includes(prop); }); // 合并并去重,得到完整属性列表 const allCSSProps = [...new Set([...longhandProps, ...supportedShorthands])]; console.log(allCSSProps);
这个方法简单直接,能覆盖绝大多数常用简写属性;唯一的缺点是需要手动维护列表,没法100%覆盖所有边缘的简写属性。
方法二:利用CSS规则注入枚举
创建一个空的CSS样式规则,枚举其style对象的所有属性,再结合CSS.supports校验:
const sheet = new CSSStyleSheet(); sheet.insertRule('* {}', 0); const ruleStyle = sheet.cssRules[0].style; // 枚举规则style对象的所有属性(包含部分简写) const ruleProps = []; for (const prop in ruleStyle) { // 过滤掉数字索引和非属性键 if (!isNaN(prop) || typeof ruleStyle[prop] !== 'string') continue; ruleProps.push(prop); } const styles = getComputedStyle(document.body); const longhandProps = Array.from({ length: styles.length }, (_, i) => styles[i]); // 合并并筛选支持的属性 const allCSSProps = [...new Set([ ...longhandProps, ...ruleProps.filter(prop => CSS.supports(prop, 'initial') && !longhandProps.includes(prop)) ])]; console.log(allCSSProps);
这种方法能自动枚举更多属性,但还是可能漏掉一些不常用的简写,而且不同浏览器的枚举结果可能有差异。
需要注意的是,没有完美的方法能100%获取所有浏览器支持的CSS属性(包括所有简写),因为不同浏览器对属性的实现和枚举逻辑有差异,但上面的方法足以覆盖绝大多数开发场景。
内容的提问来源于stack exchange,提问作者MartinM
相关产品推荐
相关产品推荐

