前端学习笔记JavaScript - 长图滚动

预览

html代码

<div class="box">
  <img src="img/long.gif" alt="长图">
  <div class="box-top"></div>
  <div class="box-bottom"></div>
</div>

css代码

  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 640px;
      height: 300px;
      border: 1px solid gray;
      margin: 100px auto;
      /*超出部门隐藏*/
      overflow: hidden;
      position: relative;
    }

    .box-top,.box-bottom{
      width: 100%;
      height: 150px;
      position: absolute;
      left: 0;
    }

    .box-top {
      top: 0;
    }

    .box-bottom {
      bottom: 0;
    }

    .box img {
      position: absolute;
      left: 0;
      top: 0;
    }

  </style>

javascript代码


<script>
  // - 获取需要操作的元素
  let img = document.querySelector("img");
  let boxTop = document.querySelector(".box-top");
  let boxBottom = document.querySelector(".box-bottom");
  let box = document.querySelector(".box");
  // - 计算最大移动距离
  let imgH = parseInt(getComputedStyle(img).height);
  let boxH = parseInt(getComputedStyle(box).height);
  let maxoffsetY = boxH - imgH;
  // - 设置计时器
  let timer = null;
  // - 获取初始高
  let offsetY = parseInt(getComputedStyle(img).top);

  // -- 向上滚动
  boxTop.onmouseenter = function () {
    move(-20);
  }
  // -- 向下滚动
  boxBottom.onmouseenter = function () {
    move(20);
  }

  // - 滚动方法
  function move(y) {
    // - 设置定时器
    timer = setInterval(function () {

      // - 实时计算y值
      offsetY +=y;

      // - y小于0 说明是向上滚从 y>0说明是想下滚动 ,根据y值来判断滚动的最大距离
      if (y< 0 && offsetY <= maxoffsetY || y > 0 && offsetY >= 0){
        // -- 到达最大距离后停止滚动
        clearInterval(timer)
        return;
      }
      img.style.top = offsetY+"px";
    },100)

  }

  boxBottom.onmouseleave = function () {
    clearInterval(timer)

  }

  boxTop.onmouseleave = function () {
    clearInterval(timer)

  }

</script>

posted @ 2020-08-21 15:03  cmg123  阅读(417)  评论(0)    收藏  举报