当我运行页面时,交集观察器就像我想要的那样工作,但是当我重新加载页面时,它会将我传送回页面(好的,这是正常的)但是当视口与目标进行事件交互时,它会立即调用函数。顺便说一句,如果这与它有任何关系,我在项目中使用 vuejs
let options = {
root: null,
rootMargin: "-20px",
threshold: 0.375,
};
const widths = ["w-1/3", "w-4/5", "w-1/2", "w-1/2", "w-1/2", "w-2/4", "w-1/2"];
function callback(entries) {
entries.forEach((entry) => {
// Each entry describes an intersection change for one observed
// target element:
// entry.boundingClientRect
// entry.intersectionRatio
// entry.intersectionRect
// entry.isIntersecting
// entry.rootBounds
// entry.target
// entry.time
});
console.log(entries);
const entry = entries[0];
if (entry.isIntersecting === true) {
document.querySelectorAll(".bar-inner").forEach((el, i) => {
widths.forEach((w, j) => {
if (i === j) {
el.classList.remove("w-0");
el.classList.add(w);
}
});
});
}
}
let observer = new IntersectionObserver(callback, options);
const tg = document.getElementById("section2");
observer.observe(tg);
似乎当您重新加载页面时,页面正在从原来的位置滚动到顶部。因此,观察者被触发。这可能是由于 PWA 服务人员造成的。您需要单独处理这种情况。如需灵感,您可以查看 - 刷新页面并保持滚动位置