1

我的目标是在元素出现在视口上之前注入一个元素(取决于惰性数据属性,默认是元素出现在视口上之前的 100px)。我如何做到这一点是通过使用getBoundingClientRect();

const LAZY_THRESHOLD_DEFAULT = 100;
TestBox.isOnScreen = function(element) {
    const reservedDistance = parseInt(element.getAttribute(THRESHOLD) || LAZY_THRESHOLD_DEFAULT, 10);
    const rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= $(window).height() &&
        rect.right <= $(window).width()
}

我像这样使用它

$(window).scroll(function() {
  if (TestBox.isOnScreen(element)) {
    // Inject the element
  }
});

我发现的一件主要事情是(我将控制台日志$(window).scrollTop()与控制台日志一起记录在何时TestBox.isOnScreen(element):检测到元素在视口上的时刻并不总是准确的。有时是 14px、5px 或正好好。

有没有人遇到过这个问题?还是我执行错了?

4

0 回答 0