如何正确创建LazyLoad es6类?

问题描述 投票:0回答:1

我使用此代码延迟加载图像-https://jsbin.com/bozulobina/1/edit?html,css,js,output

function lazyLoad() {

  const lazyImages = document.querySelectorAll("img");
  const imageObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        let image = entry.target;
        image.src = image.dataset.src;
        image.classList.remove("lazy");
        imageObserver.unobserve(image);
      }
    });
  });

  lazyImages.forEach(image => {
    imageObserver.observe(image)
  });

}
window.addEventListener('DOMContentLoaded', lazyLoad);

[尝试使用es6类重写此代码-https://jsbin.com/rejurobupa/1/edit?html,css,js,output

class LazyLoad{
  constructor(imgElement){
    this.imgElement = imgElement;
    this.interObserver()
  }
  interObserver() {
    const imageObserver = new IntersectionObserver((images, options) => {
      images.forEach(image => {
        if (image.isIntersecting) {
          let imageLazy = image.target;
          imageLazy.src = imageLazy.dataset.src;
          imageLazy.classList.remove(this.imgElement);
          imageObserver.unobserve(imageLazy);
        }
      });
    });

    lazyImages.forEach(image => imageObserver.observe(image));
  }  

}
const lazyImages = document.querySelectorAll("img");
const lazyLoad = new LazyLoad(lazyImages);
window.addEventListener('DOMContentLoaded', lazyLoad);

告诉我正确的做法,在哪里犯错?

提前谢谢您

javascript html css es6-class
1个回答
0
投票

“ this.imgElement”不是类名,它是图像数组。因此,当您尝试从classList中删除“ this.imgElement”时,它将引发错误。而且我没有任何理由这样做。因此,我注释了这一行。现在可以了,http://jsfiddle.net/rvn7pLfy/1/

class LazyLoad{
 constructor(imgElement){
  this.imgElement = imgElement;
 this.interObserver()
}
interObserver() {
 const imageObserver = new IntersectionObserver((images, options) => {
  images.forEach(image => {
    if (image.isIntersecting) {
      let imageLazy = image.target;
      imageLazy.src = imageLazy.dataset.src;
      //imageLazy.classList.remove(this.imgElement);
      imageObserver.unobserve(imageLazy);
    }
  });
 });

 lazyImages.forEach(image => imageObserver.observe(image));
}  
}
const lazyImages = document.querySelectorAll("img");
const lazyLoad = new LazyLoad(lazyImages);
window.addEventListener('DOMContentLoaded', lazyLoad);
© www.soinside.com 2019 - 2024. All rights reserved.