实现功能:
1.鼠标移出时图片自动轮播
2.鼠标移入时图片暂停轮播
3.根据点击左、右按钮时图片显示上一张、下一张
4.显示小圆点对应显示图片
准备:
1.图片多张
2.jquery-1.12.4.min.js
htm部分:
<div class="box"> <!-- 4 张图片 --> <img src="./images/shutter_1.jpg" alt=""> <img src="./images/shutter_2.jpg" alt=""> <img src="./images/shutter_3.jpg" alt=""> <img src="./images/shutter_4.jpg" alt=""> <!-- 左右箭头 --> <div id="arrowLeft"></div> <div id="arrowRight"></div> <!-- 下面的小圆点 --> <ul id="circle"> <li></li> <li></li> <li></li> <li></li> </ul> </div>
css部分:
<style> * { margin: 0; padding: 0; } .box { width: 1000px; height: 358px; position: relative; margin: 50px auto; } .box img { position: absolute; top: 0; left: 0; opacity: 0; transition: .8s; } /* 左右箭头样式开始 */ #arrowLeft, #arrowRight { width: 49px; height: 49px; background: url("images/shutter_prevBtn.png") no-repeat; position: absolute; top: 40%; cursor: pointer; } #arrowLeft { left: 20px; } #arrowRight { right: 20px; transform: rotate(180deg); } /* 左右箭头样式结束 */ /* 小圆点样式开始 */ #circle { list-style: none; position: absolute; bottom: 10px; left: 50%; margin-left: -45px; } #circle li { float: left; width: 10px; height: 10px; border-radius: 50%; background-color: #fff; margin: 10px 5px; cursor: pointer; } /* 小圆点样式结束 */ </style>
JS部分:
<script src="./js/jquery-1.12.4.min.js"></script> <script> let i = 0; // 设置一个全局的变量来作为当前图片的下标 let action = true; // 该变量用于控制用户是否能够点击,true 能点击,false 就不能点击 $('img:first').css('opacity', 1); // 刚进来的时候,默认第一张图片显示出来 $('#circle li:first').css('background-color', 'grey'); // 修改所有图片的透明度 // 接收一个参数:不透明图片的下标 const sliderPlay = function (i) { $('.box img').css('opacity', 0).eq(i).css('opacity', 1); $('#circle li').css('background-color', 'white').eq(i).css('background-color', 'grey'); } // 封装 2 个函数:图片向右切换、图片向左切换 // 图片向右切换 const rightPlay = function () { if (action) { action = false; i++; // 当 i 等于 4 的时候,说明已经过了最后一张图片了,所以重置为第一张图片 if (i === 4) { i = 0; } sliderPlay(i); } } // 图片向左切换 const leftPlay = function () { if (action) { action = false; i--; if (i === -1) { i = 3; } sliderPlay(i); } } // 为左右箭头绑定事件 $('#arrowRight').click(function () { rightPlay(); }); $('#arrowLeft').click(function () { leftPlay(); }); // 图片自动播放 let stopTimer = setInterval(rightPlay, 1500); // 鼠标移入移出 $('.box').hover(function () { // 鼠标移入时的操作 clearInterval(stopTimer); }, function () { // 鼠标移出时的操作 stopTimer = setInterval(rightPlay, 1500); }); // 小圆点 $('#circle').on('click', 'li', function () { i = $(this).index() // 可以获取到下标 sliderPlay(i); }) //图片切换完毕允许点击左右 $('img').on('transitionend', function () { action = true; }); </script>