WebApis -scroll滚动事件

156 阅读1分钟

一、滚动事件

  • 当页面进行滚动时触发的事件
  • 事件名:scroll
  • 监听整个页面滚动:
  • 监听某个元素的内部滚动直接给某个元素加即可
      //监听整个页面
		window.addEventListener("scroll",function () {
          console.log("我滚啦 你呢");

              })

      const div=document.querySelector("div");
      div.addEventListener("scroll",function () {
        console.log("div又开始滚啦");
      })

1、获取滚动距离

 window.addEventListener("scroll",function () {
        // 这个代码可以获取到当前页面的滚动距离
        console.log(document.documentElement.scrollTop);
        
      })

2、主动设置滚动距离

const button = document.querySelector('button');
      button.addEventListener('click', function () {
        // 设置页面的滚动距离
        document.documentElement.scrollTop = 200;
      });

3、滚动动画

<style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        height: 200vh;
        background-image: linear-gradient(black, red, blue, green);
      }
      a {
        width: 150px;
        height: 195px;
        position: fixed;
        bottom: 100px;
        right: 50px;
        background-image: url(./images/gotop.png);
        /* display: none; */
      }
      a:hover {
        background-image: url(./images/gotop.gif);
      }

      /* html{
        transition: 1s;
      } */
    </style>
  </head>
  <body>
    <!-- <a href="#"></a> -->
    <a href="javascript:;"></a>
   /* 
      定时器来实现 
       */

      const a = document.querySelector('a');

      window.addEventListener('scroll', function () {
        //  获取页面滚动的距离
        const scrollTop = document.documentElement.scrollTop;
        if (scrollTop > 700) {
          // 显示火箭
          a.style.display = 'block';
        } else {
          // 隐藏
          a.style.display = 'none';
        }
      });

      a.addEventListener('click', function () {
        // document.documentElement.scrollTop = 0;
        // console.log(document.documentElement); // 就是根标签 html

        // 慢慢的来设置 scrollTop 减少为0 即可
        let timeId = setInterval(function () {
          document.documentElement.scrollTop -= 20;
          console.log('定时器执行', document.documentElement.scrollTop);

          if (document.documentElement.scrollTop === 0) {
            // 清除定时器
            clearInterval(timeId);
          }
        }, 10);
      });