20.js获取页面卷去的距离以及滚到到指定位置

监听window.onscroll事件

获取上面卷去的距离:document.documentElement.scrollTop

获取左边卷去的距离:document.documentElement.scrollLeft

滚动到指定位置

执行  window.scrollTo(参数) 事件

语法1—传递数字:

        window.scrollTop(x,y)

        x—表示横向滚动的距离

        y—表示纵向滚动的距离

语法2—传递对象:

        widow.scrollTop({left:xxx,top:xxx})

        或者可以添加behavior属性,属性值为smooth,表示平滑滚动

                比如:window.scrollTo({left:10, top: 10, behavior: "smooth" })

例子:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            div {
                height: 1300px;
                width: 2000px;
                background-color: pink;
            }
        </style>
    </head>
    <body>
        <button id="btn">点击</button>
        <div></div>
        <script>
            /* 
                浏览器卷去的尺寸
                卷去的高度
                document.documentElement.scrollTop
                卷去的宽度
                document.documentElement.scrollLeft
            */

            // 页面一打开就执行了,滚动条没动就为0
            console.log(document.documentElement.scrollTop); //0

            //要用onscroll动态获取
            //浏览器上面卷去的尺寸
            window.onscroll = function () {
                console.log(document.documentElement.scrollTop);

                // 浏览器左边卷去的尺寸
                // console.log(document.documentElement.scrollLeft);
            };


            //传递数字
            // btn.onclick = function () {
            //     window.scrollTo(10, 500);
            // };

            //传递对象
            btn.onclick = function () {
                window.scrollTo({ top: 1000, behavior: "smooth" });
            };


        </script>
    </body>
</html>
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值