【前端教程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>
效果图
本文来自博客园,作者:JeckHui;
个人主页:前端实用站点推荐; 热榜资讯早读:热榜资讯-导航;
转载请注明原文链接:https://www.cnblogs.com/xiaohuizhang/p/17514781.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了