我正在构建一个编辑器工具,对于某些功能,它需要调整视口大小/缩小视口以在页面上显示更多部分。
我不控制HTML/CSS/JS的输入所有的CSS都是来自link
标签的外部CSS
问题是HTML元素在其样式中使用vh
作为height
或min-height
。
是否可以在DOM中搜索已分配vh
样式的元素?
我尝试使用getComputedStyle
,但正如函数名所示,它返回"计算"的样式,例如,如果我有一个80vh
的height
部分
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头,允许你获取它的内容