我正在构建一个编辑器工具,对于某些功能,它需要调整视口(viewport)大小/缩小视口(viewport)以在页面上显示更多部分。
我不控制HTML/CSS/JS的输入
所有 CSS 都是来自 link
标签
问题是 HTML 元素在其样式中使用 vh
作为 height
或 min-height
。
是否可以在 DOM 中搜索分配了 vh
样式的元素?
我尝试使用 getComputedStyle
但正如函数名称所示,它返回“计算”样式,例如,如果我有一个 height
为 80vh< 的部分
getComputedStyle(el).height
// will return the computed value which is on my screen "655.2px"
我希望实现的是找到这些元素并在“缩小” View 期间临时为它们分配计算值。
正如我上面提到的,样式是外部的,因此使用 style
属性不会提供我正在寻找的内容。
最佳答案
经过一些研究并感谢 fubar 的 comment为我指出 answer使用 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 header 允许您获取它的内容
关于javascript - 有没有办法找到所有在样式中使用视口(viewport)单位的 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53037889/