首页 > 解决方案 > scrollIntoView 在延迟图像加载时无法正常工作

问题描述

当页面上有延迟图像加载时,我无法让 scrollIntoView API 正常工作。

本质上,当页面加载时,我通过抓取元素querySelector,当它滚动时,由于图像加载,焦点关闭(它向下移动页面)。

我已经尝试过没有延迟图像加载的页面,它按预期工作得很好。

我不完全可以继续讨论这个问题。

标签: javascriptlazy-loadingscrolltojs-scrollintoview

解决方案


我有同样的问题,我有两种解决方法。两者都不是超级理想,但它们确实有效。

您可以尝试一些概念,其中之一是轮询滚动事件以完成,但如果您使用持续时间,您应该能够猜测整个事情。使用默认的摆动缓动将使动画减慢并在中途加速,因此您有点卡在使用线性。

这样做的想法是启动滚动动画,并在它结束之前启动另一个滚动动画。第一个动画应该让您大致到达您想要去的地方,并且在接近结尾时,文档应该已经加载了它需要的任何内容,然后第二个动画应该缩小它并滚动到正确的位置。

主动画和补丁动画需要重叠。我已经设置了它们,以便补丁动画与主动画同时完成。这可能是不好的形式。您可以尝试在主动画结束时启动补丁,或者让它超过主动画的结束。调整数字以获得您想要的结果。

这当然是骇客。

使用 jQuery,您可以获得动画完成的回调,这可能是比同时运行两者更好的方法。

首先使用 jQuery 使用 setTimeout 来猜测开始修补的时间:

$(function() {
    $('html,body').animate({ // main animation block
        scrollTop: target.offset().top
    },{
        easing: 'linear',
        duration: 800 // how long to animate in total
    });
    setTimeout(function() {
        $('html,body').animate({
            scrollTop: target.offset().top
        }, {
            easing: 'linear',
            duration: 200 // how long to patch the animation
        });
    },600); // how long to wait before starting the patch
});

其次,使用完整的 jQuery,这更干净:

$(function() {
    $('html,body').animate({
        scrollTop: target.offset().top
    },{
        duration: 600, // main animation time
        easing: 'linear',
        complete: function() {
            $('html,body').animate({
                  scrollTop: target.offset().top,
            },{
                  easing: 'linear',
                  duration: 200 // patch time, this starts after main
            });
        }
   });
});

Safari 不支持开箱即用的平滑滚动,因此需要 jQuery 或其他一些 javascript 库来完成。以下内容应该适用于 Chrome、Edge、Firefox 等:

     var source = document.getElementById('yoursourceelementid');
     source.onclick = function() {
        var target = document.getElementById('idyouwanttoscrollto'); 
        target.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
                duration: 800 // how long to animate
        });
        setTimeout(function() { // patch animation
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start',
                    duration: 200 // how long to patch
                });
        }, 600); // how long to wait before patching
     }


推荐阅读