如何使用观察者检查 div 是否可见? (也许是 Azure 服务器问题?)

How to use the observer to check if a div is visible or not? (maybe Azure server problem?)

我需要检查我页面上的元素当前是否可见(这是通过单击按钮或函数调用设置的)。

从我目前所读的内容来看,观察者似乎是正确的工具。 在我的本地机器上一切正常。但是在我的 Azure 测试服务器上出现以下错误:

Uncaught TypeError: Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element'

这是我使用的代码:

function setStatus() {
    var target = $('#sidebar_container');

    var ro = new ResizeObserver(() => {
        if (target.is(':visible')) {
            $("i.fa-user").addClass("active");
        } else {
            $("i.fa-user").removeClass("active");
        }        
    });

    // Observe element
    ro.observe(target);
}

代码是否有问题(尽管它在本地主机上运行)或者 Azure 服务器上是否有我必须检查的设置?

从您发布的代码来看,您似乎正在通过调整 window.

的大小在本地主机上测试此功能

我这么说是因为,要检查元素是否进入视口,您应该使用 Intersection Observer,而不是 Resize Observer。

您会在上面的 MDN link 中深入了解此观察器的工作原理。

要简单地检查元素是否在视口内(因此它应该是“可见的”),这是一个可能的解决方案:

// Get a reference for the target element
let element = document.querySelector('#sidebar_container');

// Create a function that will handle any intersection between some elements and the viewport.
let handleIntersection = function (entries) {

    // Loop through all the observed elements
    for (let entry of entries) {

        // Check if the element is intersecting the viewport
        if (entry.isIntersecting) {
            console.log("The following element is visible in the viewport: ", entry.target);
            // ...
        }
    }
}

const observer = new IntersectionObserver(handleIntersection);

observer.observe(element);

此外,您应该向观察者传递一个实际的 DOM 元素,而不是 jQuery 包装器。为此,最好只使用 document.querySelector 到 select 元素而不是 jQuery。 在 devtools 中,$ 符号是 querySelector 的快捷方式,因此如果您直接通过 devtools 尝试此代码,这可能会引发一些混乱。