效果图 css
* { margin: 0; padding: 0; } .container { position: relative; width: 640px; height: 480px; margin: 50px auto; overflow: hidden; } ul { list-style: none; } .main { width: 500%; } .main li { float: left; } .main li img { width: 640px; height: 480px; } aside { position: absolute; top: 50%; transform: translateY(-50%); width: 50px; height: 80px; color: #ccc; background-color: #fff; font-size: 30px; line-height: 80px; text-align: center; display: none; } .container:hover aside { display: block; } aside:hover { color: blue; } .right { right: 0; } .dot { position: absolute; bottom: 50px; right: 100px; } .dot li { float: left; width: 20px; height: 20px; background-color: #fff; border-radius: 50%; } .dot li + li { margin-left: 20px; } .active { background-color: red !important; }html
<div class="container"> <ul class="main"> <li><img src="./img/1.jpg" alt="" /></li> <li><img src="./img/2.jpg" alt="" /></li> <li><img src="./img/3.jpg" alt="" /></li> <li><img src="./img/4.jpg" alt="" /></li> <li><img src="./img/5.jpg" alt="" /></li> </ul> <aside class="left"><</aside> <aside class="right">></aside> <ul class="dot"> <li class="active"></li> <li></li> <li></li> <li></li> <li></li> </ul> </div>js
//获取父级容器 var oCon = document.getElementsByClassName("container")[0]; // 获取所有ul var oUl = document.getElementsByTagName("ul"); // 获取第二个ul指示点 var oDot = oUl[1].getElementsByTagName("li"); // 两侧按钮 var aside = document.getElementsByTagName("aside"); var index = 0, // 轮播索引 timer = setInterval(function() { // 开启计时器 animate(); }, 1000); // 左右侧动画 function animate(direction = "R") { if (direction === "R") { ++index; } else { --index; } if (index == -1) { index = 4; } else if (index == 5) { index = 0; } changeDot(); // 更改点的位置 oUl[0].style.transform = "translateX(-" + 20 * index + "%)"; //幻灯片位置改变 } // 鼠标移入事件 oCon.onmouseover = function() { clearInterval(timer); }; // 鼠标移出事件 oCon.onmouseout = function() { timer = setInterval(function() { animate("R"); }, 1000); }; // 点击左侧按钮 aside[0].onclick = function() { animate("L"); }; // 点击右侧按钮 aside[1].onclick = function() { animate("R"); }; // 改变点的位置 function changeDot() { for (var i = 0; i < oDot.length; i++) { if (i == index) { oDot[index].classList.add("active"); } else { oDot[i].classList.remove("active"); } } } // 为所有点加点击事件 for (let i = 0; i < oDot.length; i++) { oDot[i].onclick = function () { index = i - 1; // animate索引默认加1,所以这里减去 animate("R"); } }