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>

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 09:42:02       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 09:42:02       56 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 09:42:02       46 阅读
  4. Python语言-面向对象

    2024-07-11 09:42:02       57 阅读

热门阅读

  1. 【人脸识别、Python实现】PyQt5人脸识别管理系统

    2024-07-11 09:42:02       19 阅读
  2. Flutter EasyRefresh:介绍与使用指南

    2024-07-11 09:42:02       22 阅读
  3. Perl编译器架构:前端与后端的精细分工

    2024-07-11 09:42:02       21 阅读
  4. Golang 高频面试题 && 答案

    2024-07-11 09:42:02       23 阅读
  5. Spring Boot常用注解类

    2024-07-11 09:42:02       21 阅读
  6. Perl伪哈希探秘:深入理解Perl中的高级数据结构

    2024-07-11 09:42:02       20 阅读
  7. Python:引号应用、字符串应用

    2024-07-11 09:42:02       22 阅读
  8. Hadoop之HDFS重点架构原理简介

    2024-07-11 09:42:02       20 阅读
  9. Spark SQL----ALTER DATABASE

    2024-07-11 09:42:02       18 阅读
  10. SpringBoot3+Redis实现分布式锁

    2024-07-11 09:42:02       17 阅读