JavaScript - 点击按钮滚动至页面顶部

文章目录

效果

在这里插入图片描述

代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Scroll To Top</title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                height: 200vh;
            }
            div.to-top {
                position: fixed;
                right: 50px;
                bottom: 50px;
                width: 50px;
                height: 50px;
                border: 1px solid #000000;
            }
            div.to-top.hidden {
                display: none;
            }
            p {
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
        <p>6</p>
        <p>7</p>
        <p>8</p>
        
        <div class="to-top"></div>
        
        <script type="text/javascript">
            window.onload = (event) => {
                // console.log(event)
                main()
            }
            
            function main() {
                const divToTop = document.querySelector("div.to-top")
                divToTop.classList.toggle("hidden", window.scrollY === 0)
                
                window.onscroll = (event) => {
                    console.log(window.scrollY)
                    divToTop.classList.toggle("hidden", window.scrollY === 0)
                }
                
                divToTop.onclick = (event) => {
                    window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
                }
            }
        </script>
    </body>
</html>

参考

Web technology for developers > CSS: Cascading Style Sheets > position

Web technology for developers > CSS: Cascading Style Sheets > border

Web technology for developers > Web APIs > Element > Element.classList

Web technology for developers > Web APIs > DOMTokenList > DOMTokenList.toggle()

Web technology for developers > Web APIs > GlobalEventHandlers > GlobalEventHandlers.onscroll

Web technology for developers > Web APIs > Window > Window.scrollTo()

Web technology for developers > Web APIs > ScrollToOptions

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值