前端技术

jq图片无缝滚动

2018-10-20  本文已影响6人  前端来入坑
jq无缝轮播图.gif
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jq-img-sroll</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <style>
        *{margin: 0;padding: 0}
        ul{list-style: none}
        .box ul li{display: block;float: left;width: 300px;height: 300px;margin-right: -1px;background-size: cover;background-position: center center;}
        .box{height: 300px;}
        #box1,#box2{float: left}
        .wrap{position: relative;width: 800px;margin: auto;height: 300px;overflow: hidden}
        .box{position: absolute;left: 0;}
    </style>
</head>
<body>

<div class="wrap">
    <div class="box">
      <ul id="box1">
        <li style="background:url(zly.jpg) no-repeat;background-size: 100% 100%;">here is images1</li>
        <li style="background:url(zly.jpg) no-repeat;background-size: 100% 100%;">here is images2</li>
        <li style="background:url(zly.jpg) no-repeat;background-size: 100% 100%;">here is images3</li>
        <li style="background:url(zly.jpg) no-repeat;background-size: 100% 100%;">here is images4</li>
        <li style="background:url(zly.jpg) no-repeat;background-size: 100% 100%;">here is images5</li>
      </ul>
      <ul id="box2"></ul>
    </div>
  </div>

  <script>
  $(function() {
    var boxwidth = $("#box1").children().length*300;
    $(".box").css({'width':boxwidth*2 +10 + 'px'});// 动态的设置box的宽度,多设置10像素
    var timer='';//设置一个定时器
    var $box1=$('#box1').children().clone(true);/*克隆box1的子元素*/
    $('#box2').append($box1);//将复制的元素插入到#box2中
    var $left=parseInt($('.box').css('left'));//获取.box的left值
    var scroll=function(){
      $left-=2;//设置滚动速度为2
      $('.box').css('left',$left+'px');//left赋值
      if($left<-boxwidth){//当box值小于-1500px时,重置.box left值为0;实现无缝滚动
        $('.box').css('left','0');
        $left=0;
      }
      timer =setTimeout(scroll,30);
     }
    setTimeout(scroll,100);//刷新网页100ms后开始滚动
    $('.wrap').hover(function(){
      clearTimeout(timer);//鼠标滑过清除滚动
    },function(){
      setTimeout(scroll,100);//鼠标移开继续滚动
    }); 
  })
</script>

</body>
</html>

带上素材


zly.jpg
上一篇下一篇

猜你喜欢

热点阅读