<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> * { margin: 0; padding: 0; }
ul { list-style: none; }
.slider { width: 590px; height: 470px; border: 5px solid black; position: relative; overflow: hidden; }
.slider .list li { position: absolute; opacity: 0; transition: opacity .3s; }
.slider .list li.current { opacity: 1; z-index: 2; }
.btn { position: absolute; top: 50%; width: 80px; height: 40px; background: black; color: white; opacity: .3; z-index: 3; font-size: 35px; text-align: center; line-height: 40px; border-radius: 10px; cursor: pointer;
}
.btn:hover { opacity: 1; }
.prev { left: -20px; }
.next { right: -20px; }
.pagination { position: absolute; bottom: 20px; z-index: 2; left: 30px; }
.pagination li { float: left; margin-left: 10px; width: 10px; height: 10px; border-radius: 50%; background: white; opacity: .5; border: 3px solid rgba(255, 66, 0, .2); cursor: pointer; }
.pagination li:hover { opacity: 1; } </style> </head>
<body> <div class="slider"> <ul class="list"> <li class="current"><a href="#1"><img src="./imgs/pic (1).jpg" alt=""></a></li> <li><a href="#2"><img src="./imgs/pic (2).jpg" alt=""></a></li> <li><a href="#3"><img src="./imgs/pic (3).jpg" alt=""></a></li> <li><a href="#4"><img src="./imgs/pic (4).jpg" alt=""></a></li> </ul> <div class="btn prev"><</div> <div class="btn next">></div> <ul class="pagination"> <li class="bullet"></li> <li class="bullet"></li> <li class="bullet"></li> <li class="bullet"></li> </ul> </div> <script>
//定义一个全局变量,来表示当前显示的图片的索引 var currentIndex = 0;
// 将轮播切换到指定的图片上 function slideTo(index) {
if (index === 4) { index = currentIndex = 0 }
if (index === -1) { index = currentIndex = 3; } var lis = document.querySelectorAll('.slider .list li'); //清除旧焦点 //xxx.classList.remove(yyyClass) //xxx.classList.add(xxxClass)
document.querySelector('.current').classList.remove('current'); lis[index].classList.add('current')
} function slideNext() { currentIndex++ slideTo(currentIndex) } function slidePrev() { currentIndex-- slideTo(currentIndex) }
//绑定事件 document.querySelector('.slider .prev').onclick = function () { slidePrev() }
document.querySelector('.slider .next').onclick = function () { slideNext() }
var bullets = document.querySelectorAll('.pagination .bullet'); for (var i = 0; i < bullets.length; i++) { bullets[i].index = i; bullets[i].onmouseover = function () { // console.log(this.index); currentIndex = this.index; slideTo(currentIndex) } }
document.querySelector('.slider').onmouseover = function () { stop() } document.querySelector('.slider').onmouseout = function () { auto() } //自动轮播 var id; function auto() { id = setInterval(function () { slideNext(); }, 3000) }
function stop() { clearInterval(id) } auto(); </script> </body>
</html>