使用原生js实现轮播图
html代码
<div class="slide"> <ul> <li style="display: block;"> <img src="1.jpg"> </li> <li> <img src="2.jpg"> </li> <li> <img src="3.jpg"> </li> <li> <img src="4.jpg"> </li> <li> <img src="5.jpg"> </li> </ul> <span class="pre"> < </span> <span class="next"> > </span> </div>
css代码
*{padding:0; margin: 0;} ul,ol,li{list-style: none;} img{vertical-align: top; border: none;} a{text-decoration: none;} body{font-size: 14px; font-family: '微软雅黑';} .slide{ width: 250px; height: 90px; margin: 100px auto; position: relative; } .slide>ul>li{ position: absolute; float: left; display: none; } .slide>ul>li:first-child{ display:block; } .slide>ul>li>img{ width:250px; height:90px; } .slide>span{ position:absolute; top:30px; background-color: rgba(0, 0, 0, 0.3); color: #fff; display:block; width: 20px; text-align: center; height:30px; line-height: 30px; } .slide>.pre{ left:0; border-top-right-radius: 3px; border-bottom-right-radius: 3px; } .slide>.next{ right: 0; border-top-left-radius: 3px; border-bottom-left-radius: 3px; }
js代码
let index = 0; //当前索引 var pre = document.getElementsByClassName("pre")[0]; var next = document.getElementsByClassName("next")[0]; var lis = document.getElementsByClassName("slide")[0].children[0].children; next.onclick = function() { index++; for (let i = 0; i < lis.length; i++) { lis[i].style.display = "none"; } // index = index + 1 == lis.length ? 0 : index;最后一张则回到第一张 if (index == lis.length) { index = 0; } lis[index].style.display = "block"; } pre.onclick = function() { index--; for (let i = 0; i < lis.length; i++) { lis[i].style.display = "none"; } // index = index + 1 == lis.length ? 0 : index;第一张上一张则为最后一张 if (index < 0) { index = lis.length - 1; } lis[index].style.display = "block"; } function auto() { next.click(); } let s = setInterval("auto()", 2000); for (let i = 0; i < lis.length; i++) { lis[i].onmouseenter = function() { clearInterval(s); } lis[i].onmouseleave = function() { s = setInterval("auto()", 2000); } }
标签:index,none,实现,length,js,slide,lis,display,幻灯片 From: https://www.cnblogs.com/jxweber/p/16635977.html