如何查找任意给定DOM节点下带有指定CSS样式的子元素
获取带有指定样式元素的实现方案
jQuery原生的find和filter方法不支持直接按计算样式筛选,你可以通过遍历后代节点校验样式属性,或者自定义jQuery选择器实现需求。
原生JS封装实现
- 无需依赖jQuery,适配所有动态获取的
mutation.target节点
/** * 按样式属性筛选后代元素 * @param {HTMLElement} root 搜索根节点,即每次获取的 mutation.target * @param {string} styleProp 要筛选的样式属性(驼峰写法,如backgroundImage) * @param {boolean} excludeDefault 是否排除属性默认值,默认过滤backgroundImage的none值 * @returns {HTMLElement[]} 符合条件的元素数组 */ function getElementsByStyle(root, styleProp, excludeDefault = true) { const matchedEls = [] const allDescendants = root.querySelectorAll('*') for (const el of allDescendants) { const styleVal = getComputedStyle(el)[styleProp] if (styleVal && !(excludeDefault && styleVal === 'none')) { matchedEls.push(el) } } return matchedEls } // 调用示例:筛选当前变动节点下所有带background-image的元素 const bgImageElements = getElementsByStyle(mutation.target, 'backgroundImage') // 如需转jQuery对象直接使用 $(bgImageElements) 即可
自定义jQuery选择器实现
如果习惯用jQuery链式调用,可以扩展自定义选择器直接调用:
// 全局扩展jQuery选择器 $.expr[':'].hasBgImage = function(el) { return getComputedStyle(el).backgroundImage !== 'none' } // 调用示例,直接用find筛选即可 const bgImageEls = $(mutation.target).find(':hasBgImage')
注意事项
- 样式属性名需要用驼峰格式,例如
background-image对应backgroundImage、font-size对应fontSize,和DOM标准属性名保持一致 - 如果只需要判断行内样式,把
getComputedStyle(el)替换为el.style即可,遍历性能更高
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

