js writing carousel effect

  • 2021-11-01 02:15:53
  • OfStack

In this paper, we share the specific code of js to realize the carousel effect for your reference. The specific contents are as follows

1. html Part


<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 Part


 <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"
    }
    //  To the right 
    rig.onclick = function(){
      if(index !== 5){
        index++
      }
      if(index === 5){
        index = 0
    }
    setLi()
  }
  // To the left 
  lef.onclick = function(){
      
      if(index !== 0){
        index--
      }
      if(index === 0){
        index = 5
    }
    setLi()
  }
  // Dot 
  for(var i = 0;i < olList.length;i++){
    olList[i].onclick = function(){
      index = this.getAttribute("data-i")
      setLi()
    }
  }
  // Timing 
  var autoPlay = setInterval(
    function(){
      rig.click()
    },3000)

  // Draw the mouse up to stop playing 
  var box = document.querySelector("div")
  box.onmouseenter = function(){
    clearInterval(autoPlay)
  }

  //  Move the mouse and continue playing 
  box.onmouseleave = function(){
    autoPlay = setInterval(
    function(){
      rig.click()
    },3000)
  }
</script>

Related articles: