我只想在用户看到图像或当图像元素在用户视图中可见时才呈现图像。我已经尝试过了,但是只有当我已经传递了所有的图像元素,而不是一个一个地滚动时,图像才会呈现出来。
我创建一个自定义指令并将其放在我的父div上。
这是我使用Vue指令的交叉观察者:
inserted: el => {
let arrayChildren = Array.from(el.children)
const config = {
root: null,
rootMargin: '0px',
threshold: 1.0,
}
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src
observer.unobserve(entry.target)
}
})
}, config)
function getAllImgQuery() {
let imageArray = []
arrayChildren.forEach(element => {
if (element.nodeName === 'IMG') {
imageArray.push(element)
}
})
return imageArray
}
let imageQuery = getAllImgQuery()
imageQuery.forEach(image => {
observer.observe(image)
})
},这是我的Vue组件
<template>
<div id="image-container">
<div class="product">
<figure class="image-wrapper" v-lazyload>
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
<img :data-src="url" style="margin-top: 100px">
</figure>
</div>
</div>
</template>
<script>
import lazyLoadDirective from "../directives/lazyLoadImage.js";
export default {
data() {
return {
url:
"https://s2.reutersmedia.net/resources/r/?m=02&d=20190823&t=2&i=1422065068&w=1200&r=LYNXNPEF7M1OI"
};
},
directives: {
lazyload: lazyLoadDirective
}
};
</script>最后,只有当我已经看到或者交叉(当我在页面底部)时,这六个图像才会同时加载。只有在滚动传递图像之后,我才能一个一个地加载图像?
发布于 2019-08-24 15:29:07
我认为你的问题与你设定的门槛有关。我推荐阅读:API
挂载:
一个数字或一个数字数组,这些数字指示应该执行观察者的回调在目标可见性中所占的百分比。如果只想检测能见度何时超过50%的标记,则可以使用0.5值。如果您希望每次可见性超过25%时都要运行回调,则需要指定数组0、0.25、0.5、0.75、1。默认值为0(意味着只要一个像素可见,回调就会运行)。值为1.0意味着在每个像素可见之前,阈值不会被认为通过。
https://stackoverflow.com/questions/57639265
复制相似问题