轮播图效果演示:
核心原理:
我们通过对这个父盒子添加动画函数来实现移动,然后给父盒子来一个溢出隐藏就达到了轮播的效果。
HTML代码:
<div class="banner"> <!-- 主图 --> <div class="tupian"> <img src="img/002838-1667579318a9fc.jpg" alt=""> <img src="img/004111-16644696713f57.jpg" alt=""> <img src="img/004446-16674938864937.jpg" alt=""> <img src="img/215714-166627423433f6.jpg" alt=""> </div> <!-- 小点 --> <div class="biao"> <span style="background-color: rgba(255, 0, 0, 0.6);"></span> <span></span> <span></span> <span></span> </div> <!-- 左右翻 --> <div class="jiantou"> <img src="img/左箭头.png" alt=""> <img src="img/右箭头.png" alt=""> </div> </div>
CSS代码:
<style> * { margin: 0; padding: 0; } /* 主图部分 */ .banner { margin: auto; margin-top: 100px; width: 600px; height: 300px; overflow: hidden; position: relative; } .tupian { width: 400%; height: 300px; display: flex; } .tupian img { width: 25%; height: 300px; } /* 小点部分 */ .biao { width: 100%; height: 30px; display: flex; justify-content: center; margin-left: 10px; position: absolute; bottom: 0; } .biao span { width: 20px; height: 20px; display: block; border-radius: 100%; background-color: rgba(0, 0, 0, 0.7); margin-left: 10px; } .jiantou { width: 100%; height: 30px; display: flex; justify-content: space-between; position: absolute; align-items: center; position: absolute; top: 115px; text-align: center; } .jiantou img { display: block; width: 30px; height: 30px; background-color: rgba(255, 255, 255, 0.3); /* margin-left: 10px; */ } </style>
js代码:
<script> // 获取图片 let banner = document.getElementsByClassName('banner')[0]; let tupian = document.getElementsByClassName('tupian')[0]; let img = tupian.children; let tuwidth = img[0].offsetWidth; //获取图片宽度 // 获取点 let biao = document.getElementsByClassName('biao')[0]; let b = biao.children;//里面的三个点 //获取左右箭头 let jiantou = document.getElementsByClassName('jiantou')[0]; let hhh = jiantou.children let index = 0 let dingshi = setInterval(lunbo, 3000);//定时器 //鼠标放上去让图片停止 banner.onmouseover = function () { clearInterval(dingshi); } banner.onmouseout = function () { dingshi = setInterval(lunbo, 2000); } function lunbo() { if (index < img.length - 1) { index++ } else { index = 0; } for (let i = 0; i < b.length; i++) { b[i].style.backgroundColor = "rgba(0,0,0,0.7)" } b[index].style.backgroundColor = 'rgba(255, 0, 0, 0.6)' tupian.style.marginLeft = -index * tuwidth + 'px' } //左滑 hhh[0].onclick = function () { if (index > 0) { index-- } else { index = img.length - 1; } for (let i = 0; i < b.length; i++) { b[i].style.backgroundColor = "rgba(0,0,0,0.7)" } b[index].style.backgroundColor = 'rgba(255, 0, 0, 0.6)' tupian.style.marginLeft = -index * tuwidth + 'px' } //右滑 hhh[1].onclick = function () { lunbo() }

