我想观察字符串中的所有图像,如果它们进入视口,我想触发一个函数(延迟加载图像)。
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也不会触发图像元素。