繁体   English   中英

有没有办法找到所有使用样式中的视口单位的HTML元素?

[英]Is there a way to find all HTML elements that use viewport units in their styles?

我正在构建一个编辑器工具,对于某些功能,它需要调整大小/缩小视口以在页面上显示更多部分。

我无法控制HTML / CSS / JS的输入所有CSS都是来自link标记的外部CSS

问题是HTML元素在样式中使用vh作为heightmin-height

是否可以在DOM中搜索分配了vh样式的元素?

我尝试使用getComputedStyle但正如函数名称所建议的那样,它返回“计算”样式,例如,如果我有一个height80vh的部分

getComputedStyle(el).height
// will return the computed value which is on my screen "655.2px"

我希望实现的是找到这些元素,并在“缩小”视图期间临时为它们分配计算值。

正如我上面提到的,样式是外部的,因此使用style属性不会提供我想要的东西。

经过一些研究,并感谢fubar的评论 ,他使用document.styleSheets我指出了答案,因此我能够提出一种满足我需要的解决方案。

function findVhElements() {
    const stylesheets = Array.from(document.styleSheets)
    const hasVh = str => str.includes('vh');
    // this reducer returns an array of elements that use VH in their height or min-height properties 
    return stylesheets.reduce( (acc,sheet) => { 
        // Browsers block your access to css rules if the stylesheet is from a different origin without proper allow-access-control-origin http header
        // therefore I skip those stylesheets 
        if (!sheet.href || !sheet.href.includes(location.origin)) return acc
        // find rules that use 'vh' in either 'minHeight' or 'height' properties
        const targetRules = Array.from(sheet.rules).filter( ({style}) => style && (hasVh(style.minHeight) || hasVh(style.height)) )
        // skip if non were found
        if (!targetRules.length) return acc;
        // return elements based on the rule's selector that exits on the current document 
        return acc.concat(targetRules.map( ({selectorText}) =>  document.querySelector(selectorText) ).filter( el => el) ) 
    }, [])
}

该解决方案适用于我的情况,因为样式来自与脚本相同的来源,如果您要处理来自其他来源的样式,我建议您实施一个后端解决方案,或者确保其他来源提供的HTTP标头允许您获取内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM