里面有鼠标事件!
防抖功能!
还有左右小按钮!
HTML
<div class="lubotu"> <div class="tupian"> <img src="./img/ia_100000000044.jpg" alt=""> <img src="./img/ia_100000002930.jpg" alt=""> <img src="./img/ia_100000002932.jpg" alt=""> <img src="./img/ia_100000002936.jpg" alt=""> <img src="./img/ia_100000000044.jpg" alt=""> </div> <div class="anjian"> <img src="./img/ia_100000000.png" alt="" width="50px" height="50px" onclick="isLeft()"> <img src="./img/ia_100000007.png" alt="" width="50px" height="50px" onclick="isRight()"> </div> </div>
css
<style> * { margin: 0; padding: 0; } .lubotu { width: 500px; height: 350px; overflow: hidden; position: relative; } .tupian { width: 500%; height: 100%; display: flex; } .tupian img { width: 25%; height: 300px; } .anjian { width: 500px; display: flex; position: absolute; justify-content: space-between; top: 35%; } </style>
js
<script> let tupian = document.getElementsByClassName("tupian")[0]; let imgTupian = tupian.children; let lubotu = document.getElementsByClassName("lubotu")[0]; let imgWidth = imgTupian[0].offsetWidth; let index = 0; let times = setInterval(scrolls, 2000); // 轮播图/过度效果 function scrolls() { index++; tupian.style.transition = "all 1s"; tupian.style.marginLeft = -index * imgWidth + "px"; if (index == 4) { setTimeout(function() { index = 0; tupian.style.transition = ""; tupian.style.marginLeft = "0px"; }, 1000) } } // onmousemove 鼠标移动时(鼠标事件) // onmouseenter 鼠标放上去时(鼠标事件) // onmouseout 鼠标移出时(鼠标事件) lubotu.onmousemove = function() { clearInterval(times); } lubotu.onmouseout = function() { times = setInterval(scrolls, 2000); } // 左按钮向右滑动 function isLeft() { if (index == 0) { index = imgTupian.length - 1; tupian.style.transition = ""; tupian.style.marginLeft = -index * imgWidth + "px"; } setTimeout(function() { index--; tupian.style.transition = "all 1s"; tupian.style.marginLeft = -index * imgWidth + "px"; }, 0) } // 右按钮向右滑动 防抖功能 let isStatus = true; function isRight() { if (!isStatus) { return; } isStatus = false; scrolls(); setTimeout(function(){ isStatus = true; },1000) } </script>