如何检测以前在浏览器中不可见的元素的可见性?
How detect visibility of element that previously was invisible in the browser?
我正在开发一个小型分析应用程序(使用 JavaScript)并遇到了以下问题:该网站有一些不可见的元素,但有时会变得可见。例如,like here。顶部有一个菜单,当您悬停鼠标时,会出现一个子菜单。有必要检测子菜单中的 link 何时对用户可见。当 hover
主菜单中的元素时,子菜单由 CSS 呈现。该网站的结构最初是未知的,所以我无法将处理程序放在必要的元素上,该解决方案应该适用于任何网站。
我已经尝试/知道:
- 如果通过
window.getComputedStyle(element).display
查看子菜单中link的CSS 属性,则表明该元素可见。 element.getBoundingClientRect()
中只有零值表示该元素当前不可见。
- 我以为
MutationObserver
会有所帮助,但结果发现在这种情况下没有DOM变化,所以观察者不起作用。
还有什么其他解决方案?
对于遇到同样问题的每个人,我使用IntersectionObserver API解决了它。示例:
const onIntersectionChange = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
//Element become visible. Do your logic here and remove monitoring
observer.unobserve(entry.target);
}
});
};
const intersectionObserver = new IntersectionObserver(onIntersectionChange, {
threshold: 0.5
});
watchingElements.forEach(element => {
intersectionObserver.observe(element);
});
我正在开发一个小型分析应用程序(使用 JavaScript)并遇到了以下问题:该网站有一些不可见的元素,但有时会变得可见。例如,like here。顶部有一个菜单,当您悬停鼠标时,会出现一个子菜单。有必要检测子菜单中的 link 何时对用户可见。当 hover
主菜单中的元素时,子菜单由 CSS 呈现。该网站的结构最初是未知的,所以我无法将处理程序放在必要的元素上,该解决方案应该适用于任何网站。
我已经尝试/知道:
- 如果通过
window.getComputedStyle(element).display
查看子菜单中link的CSS 属性,则表明该元素可见。element.getBoundingClientRect()
中只有零值表示该元素当前不可见。 - 我以为
MutationObserver
会有所帮助,但结果发现在这种情况下没有DOM变化,所以观察者不起作用。
还有什么其他解决方案?
对于遇到同样问题的每个人,我使用IntersectionObserver API解决了它。示例:
const onIntersectionChange = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
//Element become visible. Do your logic here and remove monitoring
observer.unobserve(entry.target);
}
});
};
const intersectionObserver = new IntersectionObserver(onIntersectionChange, {
threshold: 0.5
});
watchingElements.forEach(element => {
intersectionObserver.observe(element);
});