JS轮播

1.原生js轮播

原生的轮播效果,这里实现的原理:有个一个放置图片列表的块级元素,放置所有的图片,我这里使用的是横向的列表;他的父元素为一个展示块,宽高为一张图片的宽高,利用overflow:hidden属性,每次只展示一张图片,隐藏其他图片,再用js控制图片列表定时或者其他方式左移右移即可实现简单的轮播了。下图图片处为overflow:hidden的父元素,1500*200为图片列表。

 
image.png

为了让轮播更流畅,在最后一张图片后面插入第一张图片。

 
image.png
.box{
  width:300px;
  height:200px;
  margin:100px auto;
  overflow: hidden;
}
.img-g{
  width:1500px;
  height:200px;
}
.img-g img{
  width:300px;
  height:200px;
}

将图片列表position设为relative,就可以利用偏移来移动图片了,为了方便,这里将left属性内联到img-g里。
如left为-100px时

 
image.png

然后用js获得图片列表的style.left,使用定时器控制他的偏移量,就可以实现简单的轮播了。

let p=document.getElementsByClassName('img-g')[0];
let timer=setInterval(move,2000);
function move(){
  if(parseInt(p.style.left)>-1200){
    p.style.left=parseInt(p.style.left)-300+'px'
    console.log(p.style.left)
  }else{
    p.style.left='-300px'
  }
}

不过光有图片的移动还不够,为了让图片切换更自然一点,可以加入css3对left的过渡。
不过最后一张切换到第一张时的过渡是相反的,因此还是使用js控制过渡属性。
从最后一张图片到第一张图片的过渡稍微麻烦一些,我最后使用定时器,让图片滑到最后一张,等过渡动画完成之后,取消过渡动画,切换到第一张之后再开启动画。这部分代码如下

 
image.png
let p=document.getElementsByClassName('img-g')[0];
let timer=setInterval(move,2000);
function move(){
  if(parseInt(p.style.left)>-1200){
    p.style.left=parseInt(p.style.left)-300+'px'
    p.style.transition='left 1s';
    if(parseInt(p.style.left)<=-1200){
        console.log('t')
        setTimeout(function(){
          p.style.left='0px'
          p.style.transition='left 0s';
        },1000)
    }
  }else{
    p.style.left='0px'
    p.style.transition='left 0s';
  }
}

到这里,轮播的功能已经实现了,还可以为它加上几个小圆点,控制轮播现在正在播放的图。
小圆点html

<div class='button-g'>
      <span data-index='0' ></span>
      <span data-index='1'></span>
      <span data-index='2'></span>
      <span data-index='3'></span>
    </div>
.button-g{
  position:relative;
  top:-20px;
  text-align:center;
}
.button-g span{
  display:inline-block;
  position:relative;
  z-index:10;
  width:10px;
  height:10px;
  margin:0 5px;
  border-radius:100%;
}

小圆点被点击时,图片滑动至小圆点对应的图片,并且图片滑动时小圆点也跟着变化,我在每个小圆点属性中加入了data-属性,该属性可被js获取。
为小圆点加入事件,被点击时滑动对应的偏移量。

for(let i=0;i<button.length;i++){
  button[i].onclick=function(){
    p.style.left=-300*this.getAttribute('data-index')+'px'
    tog(this.getAttribute('data-index'))
  }
}

function tog(index){
  if(index>3){tog(0);return;}
  for(let i=0;i<button.length;i++){
    button[i].style.backgroundColor='#eee'
  }
  button[index].style.backgroundColor='rgb(215, 81, 15)';
}

常见的轮播还有一种效果,就是鼠标只在图片上的时候,暂停轮播;鼠标离开时继续轮播。
以这种思路,很容易实现想要的效果。

p.onmouseover=function(){
  clearInterval(window.timer)
}
p.onmouseout=function(){
  window.timer=setInterval(move,3000);
}

实际效果可以看下面链接:
https://zkhchris.github.io/FE_basic/hc/Carousel/carousel_pure_js.html



作者:zkhChris
链接:https://www.jianshu.com/p/5e47aae71fe0
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
posted @ 2018-11-18 19:50  小炸渣i  阅读(139)  评论(0)    收藏  举报