Gal*_*hus 6 javascript js-scrollto
我的页面上有一个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();
})();
Run Code Online (Sandbox Code Playgroud)
我的滚动到代码:
(() => {
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'
});
});
});
})();
Run Code Online (Sandbox Code Playgroud)
有没有办法来解决这个问题?
这似乎是由延迟加载期间图像尺寸更改事件引起的。
因此,您可以将固定height和width延迟加载图像设置为跳过此问题。
编辑:
由于固定图像尺寸不合适,您可以使用location.href = '#your-image-tag', plus window.scrollByin来修复此问题image.onload来修复此问题。
关键代码:
(() => {
document.querySelectorAll('a[href^="#"]').forEach((elem) => {
elem.addEventListener('click', (e) => {
e.preventDefault();
location.href = elem.getAttribute('href')
});
});
})()
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
现场演示:https://codesandbox.io/s/focused-field-2q3py? file=/src/index.js