JS缓冲运动案例:右下角悬浮窗

JS缓冲运动案例:右下角悬浮窗

红色区块模拟页面的右下角浮窗,在页面进行滚动时,浮窗做缓冲运动,最终在页面右下角停留。

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>JS小案例:右侧缓冲悬浮框</title>
  <style>
    body {
      height: 2000px;
      margin: 0px;
    }

    #div1 {
       100px;
      height: 150px;
      background: red;
      position: absolute;
      right: 0;
      bottom: 0;
    }
  </style>
  <script>
// 补充代码

  </script>
</head>

<body>
  <div id='div1'></div>
</body>

</html>

  

参考代码:

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>JS小案例:右侧缓冲悬浮框</title>
  <style>
    body {
      height: 2000px;
      margin: 0px;
    }

    #div1 {
       100px;
      height: 150px;
      background: red;
      position: absolute;
      right: 0;
      bottom: 0;
    }
  </style>
  <script>


    window.onscroll = function () {
      var oDiv = document.getElementById('div1');

      startMove();
    }

    var timer = null;

    function startMove() {
      var oDiv = document.getElementById('div1');

      clearInterval(timer);

      timer = setInterval(function () {

        var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;

        var iTarget = document.documentElement.clientHeight - oDiv.offsetHeight + scrollTop;

        var speed = (iTarget - oDiv.offsetTop) / 4;

        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

        if (oDiv.offsetTop == iTarget) {

          clearInterval(timer);

        } else {
          oDiv.style.top =oDiv.offsetTop +speed+ 'px';
        }

      }, 30)

    }

  </script>
</head>

<body>
  <div id='div1'></div>
</body>

</html>

  

原文地址:https://www.cnblogs.com/f6056/p/11284405.html