600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > JS实现轮播图点击切换 按钮切换功能

JS实现轮播图点击切换 按钮切换功能

时间:2021-09-13 08:51:52

相关推荐

JS实现轮播图点击切换 按钮切换功能

JS实现轮播图点击切换、按钮切换功能

前言轮播图案例总结

前言

轮播图的案例非常经典,写法也非常多,我在写一个自己用的比较多的写法,帮助大家理解,在网页的设计中,可以直接拿去用(记得换图片路径哦!),仅供参考学习。


轮播图案例

代码如下(示例):

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><style>* {margin: 0;padding: 0;list-style: none;}#slideshow {width: 800px;height: 600px;overflow: hidden;position: relative;margin: 50px auto;}#pre {position: absolute;top: 250px;left: 368px;width: 50px;height: 100px;font-size: 40px;opacity: 0.5;cursor: pointer;}#next {position: absolute;top: 250px;left: 1118px;width: 50px;height: 100px;font-size: 40px;opacity: 0.5;cursor: pointer;}#imglist li {position: absolute;opacity: 0;}#dotlist {position: absolute;bottom: 30px;width: 100px;display: flex;justify-content: space-between;left: 50%;transform: translate(-50%);}#dotlist > li {width: 20px;height: 20px;text-align: center;border-radius: 50%;background-color: rgb(206, 16, 16);opacity: 0.3;cursor: pointer;user-select: none;}#imglist > li.appear,#dotlist > li.appear {opacity: 1;}</style></head><body><div id="slideshow"><ul id="imglist"><li><img src="1.gif" alt=""></li><li><img src="2.gif" alt=""></li><li><img src="3.gif" alt=""></li><li><img src="4.gif" alt=""></li><li><img src="5.gif" alt=""></li></ul><ul id="dotlist"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></div><button id="pre"><</button><button id="next">></button><script>//获取元素var slideShow = document.getElementById("slideshow");var imgList = document.getElementById("imglist");var imgs = imgList.children;var dotList = document.getElementById("dotlist");var dots = dotList.children;var pre = document.getElementById("pre");var next = document.getElementById("next");var duration = 2000;var Index = 0;var count = imgList.children.length;var timer;window.onload = function () {imgList.children[0].classList.add("appear");dotList.children[0].classList.add("appear");for (var i = 0; i < dots.length; i++) {dots[i].index = i;dots[i].onclick = changeMe;}timer = setInterval(rotate, duration);slideShow.onmouseover = function (event) {clearInterval(timer);};slideShow.onmouseout = function (event) {timer = setInterval(rotate, duration);};pre.onclick = preImg;next.onclick = nextImg;}function change() {for (var i = 0; i < dots.length; i++) {dots[i].classList.remove("appear");imgs[i].classList.remove("appear");}dots[Index].classList.add("appear");imgs[Index].classList.add("appear");}//循环切换图片function rotate() {Index++;if (Index == count) {Index = 0;}change();}function preImg() {Index--;if (Index < 0) {Index = count - 1;}change();}function nextImg() {Index++;if (Index == count) {Index = 0;}change();}function changeMe() {Index = this.index;change();}</script></body></html>

效果图如下:


总结

里面的一些事件操作,我在前面的文章基本都讲到了,遇到不明白的可以翻翻我以前写的事件操作,也欢迎大家留言、私信我,我会尽力帮大家解决问题。

如果文章对你有帮助的话,请给我一个小小的点赞一波哦!每个赞和评论都是我编写文章的动力哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。