【前端教程01】用原生js实现一个轮播,支持自动播放

复制代码
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      #box .on{
         background: #bfa;
      }
      #box div{
         width: 300px;
         height: 200px;
         border: 1px solid red;
           display: none;
      }
   </style>

</head>

 
<body>
   <div id="box">
      <a href="javascript:;" id="prev"><-</a>

       <input type="button" value="aaa" class="on">
       <input type="button" value="bbb">
       <input type="button" value="ccc">

       <a href="javascript:;" id="next">-></a>
       
       <div style="display:block; background: red;"  >aaa</div>
       <div style="background: yellow">bbb</div>
       <div style=" background: blue">ccc</div>

   </div>
</body>
<script>
 var obox = document.getElementById('box')
 var pre = document.getElementById('prev')
 var next = document.getElementById('next')
 var inputs = obox.getElementsByTagName('input')
 var divs = obox.getElementsByTagName('div')
 var curIndex = 0
 var time = null
// 遍历点击按钮设置
for(let i =0; i<inputs.length; i++) {
   inputs[i].onclick = function(){
     curIndex = i
     console.log(curIndex,'=====')
      for (let j=0; j<inputs.length; j++) {
         inputs[j].className = ''
         divs[j].style.display = 'none'
      }
      inputs[i].className = 'on'
      divs[i].style.display = 'block'
   }
}

function nextFun() {
   for (let j=0; j<inputs.length; j++) {
         inputs[j].className = ''
         divs[j].style.display = 'none'
      }
      curIndex ++
      if (curIndex === inputs.length){
         curIndex = 0
      }
      inputs[curIndex].className = 'on'
      divs[curIndex].style.display = 'block' 
}
// 下一页
next.onclick = function(){  
   nextFun()
}

function preFun() {
   for (let j=0; j<inputs.length; j++) {
         inputs[j].className = ''
         divs[j].style.display = 'none'
      }
      curIndex --
      if (curIndex < 0){
         curIndex = 0
      }
      inputs[curIndex].className = 'on'
      divs[curIndex].style.display = 'block' 
}

// 上一页
pre.onclick = function(){
   preFun()
}

// 自动轮播
clearInterval(time)
 time = setInterval(function(){
   nextFun()
},500)

obox.onmouseover = function() {
   clearInterval(time)
} 
obox.onmouseout = function() {
   clearInterval(time)
   time = setInterval(function(){
   nextFun()
},500)
} 

</script>
 
</html>
复制代码

 效果图

 

posted @   JeckHui  阅读(98)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示