Vue的IntersectionObserver(Nuxt)

时间:2019-01-03 19:50:43

标签: javascript vue.js vuejs2 nuxt.js

我想观察字符串中的所有图像,如果它们进入视口,我想触发一个函数(延迟加载图像)。

HTML:

<div v-html="post.content"></div>

JS

mounted: function() {
    let parser = new DOMParser()
    let doc = parser.parseFromString(this.post.content, 'text/html')
    let lazyImages = [].slice.call(doc.querySelectorAll('img'))

    if ('IntersectionObserver' in window) {
      let lazyImageObserver = new IntersectionObserver(function (entries, observer) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            let lazyImage = entry.target
            lazyImage.src = lazyImage.dataset.src
            lazyImage.srcset = lazyImage.dataset.srcset
            lazyImage.classList.remove('lazy')
            lazyImageObserver.unobserve(lazyImage)
          }
        })
      })

      lazyImages.forEach(function (lazyImage) {
        lazyImageObserver.observe(lazyImage)
      })
    } else {
    // Possibly fall back to a more compatible method here
    }
}

问题在于,即使在图像元素上滚​​动/粘贴等时,IntersectionObserver也不会触发图像元素。

0 个答案:

没有答案