![](/img/trans.png)
[英]Intersection Observer API Fires callback even element is not in view
[英]Intersection Observer API: Callback function is not triggered on intersection
有一個用於延遲加載的 Vue 自定義指令
export default {
mounted: el => {
function loadImage() {
console.log("loadImage called!")
el.src = el.dataset.src
}
//loadImage();
function handleIntersect(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
loadImage();
console.log("loadImage called! from handleIntersect")
observer.unobserve(el);
}
});
}
function createObserver() {
const options = {
root: null,
threshold: 0
};
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(el);
}
if (window["IntersectionObserver"]) {
createObserver();
} else {
loadImage();
}
}
};
在本地注冊在 Vue 3 組件中
<template>
<figure>
<img :data-src="src" @load="imageLoaded = true" v-show="imageLoaded">
<Skeletor height="160" v-if="!imageLoaded"/>
</figure>
</template>
<script>
import lazyload from "../../../directives/lazyload"
export default {
...
directives: {
lazyload
},
data() {
return {
imageLoaded: false
}
}
}
</script>
回調 function handleIntersect不會在 Intersection 上觸發,當我在 DevTools 中檢查圖像時,圖像始終具有帶有圖像 url 的 data-src
但是,當我在指令中取消注釋調用loadImage() function 時,首先它被每個元素(總共 144 個)調用,然后我看到當圖像進入視口時,回調 function handleIntersect調用了loadImage() 。
下面的示例在視口中有 3 個圖像
代碼有什么問題? 為什么一旦對所有元素觸發 loadImages 並且在評論時根本不觸發回調 function 在 Intersection 上調用(控制台顯示沒有“調用 loadImage 的 output?”)?
感謝任何支持!
未觸發事件的原因是img的寬度/高度為零,或者只是簡單地為 Intersection Observer 設置了不存在(DevTools 顯示 style='display: none;')。 當我在自定義指令中取消注釋 loadImage() 時,它變得可見並且事件被觸發。
解決方案是將 v-lazyload 移動到 figure 並通過 img 標簽搜索 custome 指令中的目標元素,以便該 figure 始終托管一個骨架(來自 vue-skeletor 包的組件)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.