延迟加载与 ScrollTo 锚点到 ID 滚动冲突 - 在页面中途停止

时间:2021-07-21 09:54:25

标签: 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();

})();

我滚动到代码:

(() => {
    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'
            });
        });
    });
})();

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

这似乎是延迟加载时图像大小更改事件引起的。

因此,您可以将固定 heightwidth 设置为延迟加载图像,以跳过此问题。

<块引用>

编辑:

由于固定图像大小不合适,您可以使用 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