繁体   English   中英

使用 window.requestAnimationFrame() 将 jQuery animate({scrollLeft: x}) 迁移到 vanilla JS

[英]Migrate jQuery animate({scrollLeft: x}) to vanilla JS using window.requestAnimationFrame()

我正在尝试迁移一些 jQuery 代码,这些代码在单击其图像时(将单击的图像放在浏览器视口的中心)在水平图像库中执行平滑滚动(来回):

jQuery:

$('.page-template-format-horizontal .exhibit-image').on('click', function (e) {
    var slideWidth = $(this).width();
    var windowWidth = $(window).width();
    var scrollTo = $(this).position().left;
    var offset = scrollTo - (windowWidth / 2) + (slideWidth / 2);
    $('html, body').animate({
        scrollLeft: offset
    }, 500);
    e.preventDefault();
});

这是我想出的普通 JS 代码。 我知道我可以使用behaviour: 'smooth' window.scrollBy() ,但我想改用window.requestAnimationFrame() function,因为我需要支持一些较旧的 8837867556'588 版本支持平滑行为选项。

记者:

document.querySelector('.page-template-format-horizontal .exhibit-image').addEventListener('click', function (e) {
    var slideWidth = e.currentTarget.getBoundingClientRect().width;
    var windowWidth = window.innerWidth;
    var scrollTo = e.currentTarget.offsetLeft;
    var offset = scrollTo - (windowWidth / 2) + (slideWidth / 2);

    var duration = 50;
    var startLocation = window.pageXOffset;
    var endLocation = offset;
    var distance = endLocation - startLocation;
    var increments = distance / (duration / 16);

    function step() {
        window.scrollBy(increments, 0);
        if ( window.pageXOffset <= endLocation) {
            window.requestAnimationFrame(step);
        }
    }
    window.requestAnimationFrame(step);
    e.preventDefault();
});

它非常有效,但只是在向右滚动时,而不是向左滚动。 任何帮助,将不胜感激。

我设法自己解决了这个问题。 这是我想出的代码:

document.querySelectorAll('.page-template-format-horizontal .exhibit-image').forEach(function(item) {
    item.addEventListener('click', function (e) {
        var slideWidth = e.currentTarget.getBoundingClientRect().width;
        var windowWidth = window.innerWidth;
        var scrollTo = e.currentTarget.offsetLeft;
        var startLocation = window.pageXOffset;
        var endLocation = scrollTo - (windowWidth / 2) + (slideWidth / 2);
        var distance = endLocation - startLocation;
        var duration = 400;
        var easing = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }
        var start;

        if (!distance) {
            return;
        }

        function step(timestamp) {
            start = start || timestamp;
            var time = timestamp - start;
            var percent = Math.min(time / duration, 1);
            percent = easing(percent);
            window.scrollTo(parseInt(startLocation + distance * percent), window.scrollY);
            if (time < duration) {
                window.requestAnimationFrame(step);
            }
        }
        window.requestAnimationFrame(step);
        e.preventDefault();
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM