25

所以当全屏部分在视口中时,我试图调用一些函数。假设我有 7 个部分,那么当某个部分位于视口内时,我希望发生一些事情(我有一个将这些部分捕捉到视口中的功能,因此视口中永远不会有多个部分,但我试图找到出哪个部分在视口中可见)。

这是一个小提琴:http: //jsfiddle.net/h7Hb7/2/

function isInViewport() {
    $("section").each(function () {
        var $this = $(this),
            wHeight = $(window).height(),
            rect = $this.getBoundingClientRect(); // Error in console

        // Borrowed from http://stackoverflow.com/a/7557433/5628
        if (rect.top >= 0 && rect.bottom <= wHeight) {
            console.log($this.attr("id") + "in viewport");
        }
    });
}

$(window).scroll(function () {
    // Other functions are called inside the setTimeout function, can't remove
    clearTimeout($.data(this, "scrollTimer"));
    $.data(this, "scrollTimer", setTimeout(function () {
        isInViewport();
    }, 1200));
});

我不知道从哪里开始寻找,但我猜这与每个功能有关。是不是每个功能都有问题?这不可能是 CSS 问题,因为当 CSS 已加载时,滚动时会出现问题。

4

3 回答 3

29

您可以坚持使用 jQuery 并使用数组 [] 表示法,即:

var myClient = $(currentGrid)[0].getBoundingClientRect();
alert(myClient.top)
于 2015-07-20T20:55:57.993 回答
27

jQuery object doesn't have getBoundingClientRect method, you should get the HTMLElement object and then call the method or:

this.getBoundingClientRect();

As a suggestion, if using a plugin is an option, you can consider using the jquery.inview plugin.

于 2014-08-04T13:01:38.270 回答
0

您可以通过函数和使用 e.target.getBoundingClientRect()函数传递事件。它会工作

于 2021-09-23T06:35:35.160 回答