我需要找到一种性能非常好的方法来确定定制元素或其任何父元素是否具有display: none;
第一种方法:
checkVisible() {
let parentNodes = [];
let el = this;
while (!!(el = el.parentNode)) {
parentNodes.push(el);
}
return [this, ...parentNodes].some(el => getComputedStyle(el).display === 'none')
}
还有比这更快的吗?这是一个安全的方法吗?
我需要这个的原因是:我们有一个<data-table>
自定义元素(本地web组件),它在connectedCallback()
中执行了非常繁重的任务。我们有一个应用程序,在一个页面中有20-30个这样的自定义元素,这导致IE 11需要大约15秒才能呈现页面。
我需要延迟那些<data-table>
组件的初始化,这些组件最初甚至是不可见的,因此我需要一种方法来测试connectedCallback()
内部的元素是否可见(如果它位于最初未显示的18个选项卡中的一个,则不可见)。
3条答案
按热度按时间lc8prwob1#
查看元素或其父元素是否具有
display:none
的最简单方法是使用el.offsetParent
。这段代码将
el.offsetParent
转换为一个布尔值,表示元素是否显示。这仅适用于
display:none
dnph8jn42#
不确定性能如何,但至少应该比您的方法快:
e4eetjau3#
对于满足以下条件的纯函数:
可以定义以下函数,然后在要验证的元素上调用该函数: