JS 27 - 平滑滚动,让视窗不再是闪电侠!

大家好!

我们今天要实作让视窗能平滑地滚动到锚点。
我们进入今天的主题吧!


程序码

(function (duration) {
    Felix('a[href^="#"]').on('click', scroll);

    function ease(t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t + b;
        return -c / 2 * ((--t) * (t - 2) - 1) + b;
    }

    function scroll(e) {
        e.preventDefault();
        const anchor = Felix(encodeURI(this.hash))[0];
        const aPos = anchor.getBoundingClientRect().top;
        const wPos = window.pageYOffset;
        let startTime = null;

        function animation(currentTime) {
            if (startTime === null) startTime = currentTime;
            const time = currentTime - startTime;
            window.scrollTo(0, ease(time, wPos, aPos, duration));
            if (time < duration) requestAnimationFrame(animation);
            else {
                anchor.tabIndex = -1;
                anchor.focus();
            }
        }
        requestAnimationFrame(animation);
    }
})(1000);

上方的 ease 函式是用来调整页面滚动的加速度,每次呼叫 animation 函式时就会提供 Y 轴的座标。
关於更多加速度函式,可参考 easings.netspicyyoghurt.com 上的说明。


实测

<header id="header">
    <a href="#footer">Footer</a>
</header>
<footer id="footer">
    <a href="#header">Header</a>
</footer>

直接观看范例


差不多也到尾声了。
如果对文章有任何疑问,也欢迎在下方提问和建议!
我是 Felix,我们明天再见!


<<:  [Day27] JSON

>>:  Day 28 - [Android APP] 06-RecyclerView与资料显示

DAY22 类神经网路之架设与训练

前面我们介绍了影像辨识的资料前处理方法,今天就要开始教大家架设一个神经网路,并将资料丢入来看看实际的...

【Day 19】JavaScript 宣告和变数

何谓JavaScript? 根据MND定义,JavaScript 是一种脚本,也能称它为程序语言,可...

认识 CSS animation 与他的孩子们 (一)

keyframes 定义关键影格的各自状态,不同关键影格组成动态变化,但我们在定义keyframes...

[Day 22] 从GEIT建立政策及组织结构

接续上一章,Governance and Management of Enterprise IT (...

Day 28 - 使用 CDK 创建 CloudWatch Alarm 的含图告警同时发送到 LINE 与 Discord

昨天教大家怎麽简单的在 LINE Notify 上面看到 CloudWatch 的 Alarm,不过...