2

我有一个修改后的 Bootstrap 4 轮播,它有多个项目并使用这个 JavaScript 逐个滚动:

$('.carousel[data-type="multi"] .carousel-item').each(function() {
var next = $(this).next();
if (!next.length) {
  next = $(this).siblings(':first');
}
next.children(':first-child').clone().appendTo($(this));
for (var i = 0; i < 2; i++) {
  next = next.next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));
}
});

这将创建具有多个轮播列的每个轮播项的克隆,如下所示:

<div class="carousel-item active">
  <div class="carousel-col">
    <img src="" class="lazy" /> <!-- This image loads -->
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
</div>

<div class="carousel-item">
  <div class="carousel-col">
    <img src="" class="lazy" /> <!-- This image loads -->
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
  <div class="carousel-col">
    <img src="" class="lazy" />
  </div>
</div>

我正在尝试使用 Intersection Observer API 实现延迟加载,但是在轮播中,它仅适用于每个轮播项目中第一个轮播列中的图像。我猜这是由于克隆,但我不确定如何解决冲突。API 看不到识别克隆图像的存在。

有人对我如何解决这个问题有任何见解吗?

这是我用于延迟加载的 JavaScript:

document.addEventListener("DOMContentLoaded", function() {
  var lazyloadImages;    

  if ("IntersectionObserver" in window) {
    lazyloadImages = document.querySelectorAll(".lazy");
    var imageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          var image = entry.target;
          image.src = image.dataset.src;
          image.classList.remove("lazy");
          imageObserver.unobserve(image);
        }
      });
    });

    lazyloadImages.forEach(function(image) {
      imageObserver.observe(image);
    });
  } else {  
    var lazyloadThrottleTimeout;
    lazyloadImages = document.querySelectorAll(".lazy");
    
    function lazyload () {
      if(lazyloadThrottleTimeout) {
        clearTimeout(lazyloadThrottleTimeout);
      }    

      lazyloadThrottleTimeout = setTimeout(function() {
        var scrollTop = window.pageYOffset;
        lazyloadImages.forEach(function(img) {
            if(img.offsetTop < (window.innerHeight + scrollTop)) {
              img.src = img.dataset.src;
              img.classList.remove('lazy');
            }
        });
        if(lazyloadImages.length == 0) { 
          document.removeEventListener("scroll", lazyload);
          window.removeEventListener("resize", lazyload);
          window.removeEventListener("orientationChange", lazyload);
        }
      }, 20);
    }

    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
  }
});

4

0 回答 0