js編寫輪播圖效果

本文實例為大傢分享瞭js實現輪播圖效果的具體代碼,供大傢參考,具體內容如下

1、html部分

<div id="box">
    <ul>
      <li class="show"><img src="img/1.jpg" alt=""></li>
      <li><img src="img/2.jpg" alt=""></li>
      <li><img src="img/3.jpg" alt=""></li>
      <li><img src="img/4.jpg" alt=""></li>
      <li><img src="img/5.jpg" alt=""></li>
      <li><img src="img/6.jpg" alt=""></li>
    </ul>
    <img src="img/l.png" alt="" id="lef">
    <img src="img/r.png" alt="" id="rig">
    <ol>
      <li class="focus" data-i = "0"></li>
      <li data-i = "1"></li>
      <li data-i = "2"></li>
      <li data-i = "3"></li>
      <li data-i = "4"></li>
      <li data-i = "5"></li>
    </ol>
</div>

2、js部分

 <script>
    var liList = document.querySelectorAll("#box ul li")
    var olList = document.querySelectorAll("#box ol li")
    var rig = document.getElementById("rig")
    var lef = document.getElementById("lef")

    var index = 0
    function setLi(){
      for(var i = 0;i <liList.length;i++){
        liList[i].className = ""
        olList[i].className = ""
      }
      liList[index].className = "show"
      olList[index].className = "focus"
    }
    // 向右
    rig.onclick = function(){
      if(index !== 5){
        index++
      }
      if(index === 5){
        index = 0
    }
    setLi()
  }
  //向左
  lef.onclick = function(){
      
      if(index !== 0){
        index--
      }
      if(index === 0){
        index = 5
    }
    setLi()
  }
  //圓點
  for(var i = 0;i < olList.length;i++){
    olList[i].onclick = function(){
      index = this.getAttribute("data-i")
      setLi()
    }
  }
  //計時
  var autoPlay = setInterval(
    function(){
      rig.click()
    },3000)

  //鼠標劃上停止播放
  var box = document.querySelector("div")
  box.onmouseenter = function(){
    clearInterval(autoPlay)
  }

  // 鼠標移走繼續播放
  box.onmouseleave = function(){
    autoPlay = setInterval(
    function(){
      rig.click()
    },3000)
  }
</script>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: