JS实现轮播图效果
程序员文章站
2022-07-02 19:30:40
本文实例为大家分享了js实现轮播图展示的具体代码,供大家参考,具体内容如下
原理介绍
1.html
本文实例为大家分享了js实现轮播图展示的具体代码,供大家参考,具体内容如下
原理介绍
1.html
<div id="swiper-container" class="swiper-container" onmouseenter="swiperimg()" onmouseleave="stopswiper()"> <div id="img-list" style="left:0px;"> <img src="img/swiper1.png" alt="1"> <img src="img/swiper2.png" alt="2"> <img src="img/swiper1.png" alt="1"> <img src="img/swiper2.png" alt="2"> </div> <div id="swiper-btn"> <span index="1" class="on"></span> <span index="2"></span> </div> </div>
布局很简单,利用一个class="swiper-container"的div,包裹图片列表,swiper-btn是按钮
2. css
* { margin: 0; padding: 0; } a { text-decoration: none; } .swiper-container { position: relative; width: 300px; height: 300px; margin: 0 auto; border: 1px solid; overflow: hidden; } #img-list { position: absolute; width: 1200px; height: 300px; } #img-list img { float: left; } #swiper-btn { position: absolute; bottom: 5%; left: 45%; } #swiper-btn span { display: inline-block; width: 10px; height: 10px; border-radius: 5px; } .on { background-color: goldenrod; } span { background-color: #d7d7d7; }
3.js
var timer; var div = document.getelementbyid('img-list'); var span = document.getelementbyid('swiper-btn').getelementsbytagname('span'); var offset = -300; var index = 1; function swiperimg() { timer = setinterval(() => { var left = parseint(div.style.left); var newleft = left + offset; if (newleft <= -1200) { div.style.left = '0px'; } else { div.style.left = newleft + 'px'; } showbtn(parseint(div.style.left)); }, 3000); } function showbtn(left) { if (left == 0 || left == -600) { span[0].classname = "on"; span[1].classname = ""; } else { span[0].classname = ""; span[1].classname = "on"; } } function stopswiper() { clearinterval(timer); } for (var i = 0; i < span.length; i++) { span[i].onclick = function () { if (this.classname == "on") { return false; } var myindex = parseint(this.getattribute("index")); if (myindex == 1) div.style.left = 0 + 'px'; if (myindex == 2) div.style.left = -300 + 'px'; index = myindex; showbutton(); } } function showbutton() { for (var i = 0; i < span.length; i++) { //全部取消掉on样式 if (span[i].classname == "on") { span[i].classname = ""; break; } } span[index - 1].classname = "on"; }
效果如下所示:
上一篇: jQuery实现轮播图效果demo
下一篇: js实现带搜索功能的下拉框