无缝滚动轮播图(3)

我吃了炫迈做出来的轮播图,停不下来的那种

一、结构

<div class="box" id="screen">
  <ul>
    <li><img src="http://img.mp.itc.cn/upload/20161107/033dc0a68d084597a0c53d4028fc0cc6.jpeg" alt=""/></li>
    <li><img src="http://img.mp.itc.cn/upload/20161107/848040a29b204269a3b051505c17a59e.jpeg" alt=""/></li>
    <li><img src="http://img.mp.itc.cn/upload/20161107/cec0ebec6056473da336530c8b28b65e.jpeg" alt=""/></li>
    <!--放置了一个假的第一张,为了制作无缝滚动效果-->
    <li><img src="http://img.mp.itc.cn/upload/20161107/033dc0a68d084597a0c53d4028fc0cc6.jpeg" alt=""/></li>
  </ul>
</div>

二、样式

<style>
    * {
      margin: 0;
      padding: 0;
    }
    ul {
      list-style: none;
    }
    img {
      vertical-align: top;
    }
    /*取消图片底部3像素距离*/
    .box {
      width: 300px;
      height: 200px;
      margin: 100px auto;
      background-color: pink;
      position: relative;
      overflow: hidden;
    }
    .box ul li {
      float: left;
    }
    .box ul {
      width: 1500px;
      position: absolute;
      left: 0;
      top: 0;
    }
 </style>

三、行为

<script>
  //1 获取元素
  var screen = document.getElementById("screen");//可视区域
  var imgWidth = screen.offsetWidth;//图片宽度
  var list = screen.children[0];//要运动的ul
  var lisLen = list.children.length;//获取li的个数
  
  //2.2 设置步长
  var step = -10;
  
  //2 书写一个简单运动代码
  setInterval(function () {
  //2.1 获取元素当前位置
  var current = list.offsetLeft;
    
  //2.4 设置需要抽回的条件(当假的第一张显示完全时设置抽回操作)
  if (current > -(lisLen - 1) * imgWidth) {
    //2.3 计算新的步长,再设置给left属性即可
    current = current + step;
    list.style.left = current + "px";
  } else {
      //设置抽回操作,为了看起来没有卡顿,可以抽回到一个step的距离(设置left值为step)
      list.style.left = step + "px";
    }
  }, 40);

 //3 鼠标移入,让运动速度减慢
 screen.onmouseover = function () {
   step = -2;
  };
  
  //4 鼠标移出,将速度还原
  screen.onmouseout = function () {
    step = -10;
  };
</script>

猜你喜欢

转载自blog.csdn.net/weixin_40589472/article/details/83962613