js编写轮播图效果

时间:2022-06-08 06:29:47

本文实例为大家分享了js实现轮播图效果的具体代码,供大家参考,具体内容如下

1、html部分

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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部分

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_54741536/article/details/114499250