每个中的getBoundingClientRect:undefined不是函数

时间:2014-08-04 12:58:22

标签: javascript jquery getboundingclientrect

所以当全屏部分在视口中时,我试图调用一些函数。让我们说我有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已经加载时会在滚动时出现问题。

2 个答案:

答案 0 :(得分:23)

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

var myClient = $(currentGrid)[0].getBoundingClientRect();
alert(myClient.top)

答案 1 :(得分:19)

jQuery对象没有getBoundingClientRect方法,你应该得到HTMLElement对象,然后调用方法或:

this.getBoundingClientRect();

作为建议,如果使用插件是一个选项,您可以考虑使用jquery.inview插件。

相关问题