全屏滚动原理

本文将深入探讨全屏滚动(Full Page Scrolling)的原理,包括如何利用CSS和JavaScript来创建平滑的滚动效果,以及如何实现页面锚点链接与滚动同步。我们将讨论关键的技术细节,如滚动事件监听、滚动定位计算以及性能优化策略。
        html,
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .page {
            width: 100%;
        }

        .page:nth-of-type(1) {
            background-color: orange;
        }

        .page:nth-of-type(2) {
            background-color: skyblue;
        }

        .page:nth-of-type(3) {
            background-color: pink;
        }

        .page:nth-of-type(4) {
            background-color: darkgray;
        }
    <div id="wrap">
        <div class="page"></div>
        <div class="page"></div>
        <div class="page"></div>
        <div class="page"></div>
    </div>
        fullScroll('wrap')
        function fullScroll(id) {
            const wrap = document.getElementById(id)
            const height = document.documentElement.clientHeight
            let timer = { start: 0, end: 0, count: 0 }

            for (let i = 0, len = wrap.children.length; i < len; i++) {
                wrap.children[i].style.height = height + 'px'
            }

            let scrollFun = (e) => {
                if (e.wheelDelta === 0) return
                let dir = Boolean(e.wheelDelta < 0)
                timer.start = Date.now()

                if (timer.start - timer.end > 1000) {
                    timer.end = Date.now()
                    let y;

                    if (dir) {
                        if (timer.count < wrap.children.length) {
                            y = height * (++timer.count)
                            window.scrollTo({
                                top: y,
                                behavior: "smooth"
                            })
                        }
                    } else {
                        if (timer.count > 0) {
                            y = height * (--timer.count)
                            window.scrollTo({
                                top: y,
                                behavior: "smooth"
                            })
                        }
                    }
                }
            }

            if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                document.addEventListener("DOMMouseScroll", scrollFun);
            } else if (document.addEventListener) {
                document.addEventListener("mousewheel", scrollFun, false);
            } else if (document.attachEvent) {
                document.attachEvent("onmousewheel", scrollFun);
            } else {
                document.onmousewheel = scrollFun;
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值