> 类型:常用技巧 > 难度:★★☆ **封装一个特性检测函数,用以验证当前浏览器是否支持某个 CSS 属性** > 注:需要兼容 IE8+(含)以及其他主流浏览器 ```js /** * @param {string} [prop] - 需要验证的 CSS 属性名。 * @return: 1. 当 `prop` 为字符串时,返回当前浏览器是否支持该 CSS 属性的布尔值 2. 当 `prop` 为空时,返回一个由当前浏览器支持的所有 CSS 属性名组成的数组 */ function supported(prop) { // 你的代码 } ``` **测试用例:** (以下结果来自 Chrome 74) ```js supported('animation'); // true supported('background-clip'); // true supported('mix-blend-mode'); // true supported('-webkit-user-drag'); // true supported('-moz-force-broken-image-icon'); // false supported('-ms-block-progression'); // false supported('abcd'); // false supported(); // ["align-content", "align-items", "align-self" ... ] ``` ---- **参考答案:** ```js function supported(prop) { var result = []; var format = function(p) { // 浏览器前缀处理 var prefix = /^([webkit|moz|ms|o]+)[A-Z]+.*/.test(p) ? '-' : ''; return prefix + p.replace(/[A-Z]/g, '-$&').toLowerCase(); }; if (Object.hasOwnProperty('keys') && Object.keys(document.body.style).length) { result = Object.keys(document.body.style).map(format); } else { for (var key in document.body.style) { result.push(format(key)); } } // 兼容 IE8 if (!('indexOf' in Array.prototype)) { result = String(result); } if (typeof prop === 'undefined') { return typeof result === 'string' ? result.split(',') : result; } return result.indexOf(prop) === -1 ? false : true; } ``` ---- **本期优秀回答者:** 无 [哭笑.jpg]
Activity
liwenkang commentedon May 17, 2019
答案参考: CSS 模块的侦测
wingmeng commentedon May 17, 2019
返回的CSS属性名还是驼峰体,不对哦~