【问题标题】:getBoundingClientRect in each: undefined is not a functiongetBoundingClientRect 在 each: undefined is not a function
【发布时间】:2014-08-04 12:58:22
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery getboundingclientrect


    【解决方案1】:

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

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

    【讨论】:

    • @UnnamedSentientBeing 因为对象中的第一项是 HtmlElement。
    【解决方案2】:

    jQuery 对象没有getBoundingClientRect 方法,你应该获取 HTMLElement 对象然后调用该方法或者:

    this.getBoundingClientRect();
    

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

    【讨论】:

    • 啊,我真傻。 jQuery 是一个非常易于使用的库,但有时它会让您忽略一些就在您眼皮底下的东西!我认为一个插件会有点矫枉过正,你认为它比我的小sn-p提供更多吗?
    • 我收回了这一点,显然它似乎可以做很多事情!我特别喜欢您如何解除绑定并将其与one() 结合使用。感谢您的提示!
    • this.getBoundingClientRect() 在使用纯 Javascript 的 for 中也不起作用。
    • @thednp 没有什么能阻止getBoundingClientRect 方法在for 循环中工作。
    • @Vohuman 是的,我后来想通了,我试图获取 getBoundingClientRect 的索引值而不是实际项目。我的坏
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-24
      • 2021-06-21
      • 1970-01-01
      • 2015-06-13
      • 2014-08-15
      • 2015-01-14
      • 2014-07-06
      • 2014-09-01
      相关资源
      最近更新 更多