【问题标题】:Smoothly scrolling to element using vanilla JavaScript [duplicate]使用 vanilla JavaScript 平滑滚动到元素 [重复]
【发布时间】:2016-04-14 10:09:01
【问题描述】:

我在尝试使用 vanilla JavaScript 平滑滚动到某个元素时遇到了一些问题。

我有一个包含 3 个链接的单页网站。当我单击其中一个链接时,我希望平滑滚动到它所代表的部分。我有一个 jQuery 版本,效果很好,但我想学习如何使用 vanilla JavaScript 实现相同的结果。

之前有人问过这个问题,但答案有点复杂。我相信应该有一个更清晰、更简单的答案。

谢谢。

jQuery 代码:

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 1000);
    return false;
});

【问题讨论】:

  • 到底出了什么问题?提供一个小提琴。
  • 我想获得与 jQuery 代码相同的结果,但使用 vanilla Javascript。我不知道如何实现它。如果熟悉 Javascript 的人可以编写代码,我将不胜感激。

标签: javascript


【解决方案1】:

你需要一些缓动函数来平滑 vanilla js 滚动。

Robert Penner 是放松的人

我有一个demo on jsbin,前段时间我为 HTML5 课程做过。您可能对来源感兴趣。

上例中使用的滚动演示函数:

function scrollToItemId(containerId, srollToId) {

        var scrollContainer = document.getElementById(containerId);
        var item = document.getElementById(scrollToId);

        //with animation
        var from = scrollContainer.scrollTop;
        var by = item.offsetTop - scrollContainer.scrollTop;
        if (from < item.offsetTop) {
            if (item.offsetTop > scrollContainer.scrollHeight - scrollContainer.clientHeight) {
                by = (scrollContainer.scrollHeight - scrollContainer.clientHeight) - scrollContainer.scrollTop;
            }
        }

        var currentIteration = 0;

        /**
         * get total iterations
         * 60 -> requestAnimationFrame 60/second
         * second parameter -> time in seconds for the animation
         **/
        var animIterations = Math.round(60 * 0.5); 

        (function scroll() {
            var value = easeOutCubic(currentIteration, from, by, animIterations);
            scrollContainer.scrollTop = value;
            currentIteration++;
            if (currentIteration < animIterations) {
                requestAnimationFrame(scroll);
            }    
        })();

        //without animation
        //scrollContainer.scrollTop = item.offsetTop;

    }

    //example easing functions
    function linearEase(currentIteration, startValue, changeInValue, totalIterations) {
        return changeInValue * currentIteration / totalIterations + startValue;
    }
    function easeOutCubic(currentIteration, startValue, changeInValue, totalIterations) {
        return changeInValue * (Math.pow(currentIteration / totalIterations - 1, 3) + 1) + startValue;
    }

【讨论】:

  • 感谢 michaPau 的回答。难道没有更简单的方法吗?
猜你喜欢
  • 2011-07-02
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 2019-01-12
相关资源
最近更新 更多