我的页面上有一个 scrollTo 功能,当您单击特定按钮时,您可以滚动到具有唯一 ID 的部分。
问题是我对网站上的图像使用延迟加载,因此,由于图像是延迟加载的,这将导致 ScrollTo 在页面中途停止。
毕竟,图像已加载,我再次单击按钮,它工作正常。
我的懒加载代码:
(() => {
const runLazy = () => {
let images = [...document.querySelectorAll('[data-lazy]')];
const settings = {
rootMargin: '0px',
threshold: 0.02
};
let observer = new IntersectionObserver((imageEntites) => {
imageEntites.forEach((image) => {
if (image.isIntersecting) {
observer.unobserve(image.target);
image.target.src = image.target.dataset.lazy;
image.target.onload = () =>
image.target.classList.add('loaded');
}
});
}, settings);
images.forEach((image) => observer.observe(image));
};
runLazy();
})();
我滚动到代码:(() => {
document.querySelectorAll('a[href^="#"]').forEach((elem) => {
elem.addEventListener('click', (e) => {
e.preventDefault();
let block = document.querySelector(elem.getAttribute('href')),
offset = elem.dataset.offset
? parseInt(elem.dataset.offset)
: 0,
bodyOffset = document.body.getBoundingClientRect().top;
window.scrollTo({
top: block.getBoundingClientRect().top - bodyOffset + offset,
behavior: 'smooth'
});
});
});
})();
有没有办法来解决这个问题?
最佳答案
这似乎是由延迟加载期间图像大小更改事件引起的。
所以你可以设置固定 height
和 width
到延迟加载图像,跳过这个问题。
Edit:
由于固定图像大小不合适,您可以使用
location.href = '#your-image-tag'
修复此问题。 , 加 window.scrollBy
在 image.onload
事件。关键代码:
(() => {
document.querySelectorAll('a[href^="#"]').forEach((elem) => {
elem.addEventListener('click', (e) => {
e.preventDefault();
location.href = elem.getAttribute('href')
});
});
})()
image.target.onload = () => {
image.target.classList.add("loaded");
// TODO: check current image below or upper the target image
window.scrollBy(0, image.target.clientHeight)
// or window.scrollBy(0, 0 - image.target.clientHeight)
}
现场演示:https://codesandbox.io/s/focused-field-2q3py?file=/src/index.js
关于javascript - 延迟加载与 ScrollTo anchor 到 ID 滚动冲突 - 在页面中途停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68467475/