实例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <title>幻灯</title> <style> .box { width: 1920px; height: 500px; } .box ul { padding: 0; margin: 0; } /*初始化时,必须先把全部图片先隐藏*/ .box ul:first-of-type li { list-style: none; display: none; } .box ul:last-of-type { text-align: center; margin-top: -50px; } .box ul:last-of-type li{ list-style: none; display: inline-block; width: 26px; height: 26px; line-height: 26px; background-color: black; color: white; border-radius: 50%; margin: 0 5px; } .box ul:last-of-type li:hover { cursor: pointer; background-color: white; color: black; } </style> </head> <body> <div class="box"> <ul class="slider"> <!-- 只需要将指定的某一个显示出来即可,其它的用JS控制--> <li style="display: block" id="active"><img src="static/images/banner1.jpg" alt=""></li> <li><img src="static/images/banner2.jpg" alt=""></li> <li><img src="static/images/banner3.jpg" alt=""></li> </ul> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </div> <script> $(function(){ // 先获取所有li var lis = $('.box ul:last-of-type li'); // 获取当前图片 var img = $('#active img'); // 添加点击事件 lis.each(function(index,element){ element.onclick = function(){ img.attr('src','static/images/banner'+ parseInt(index+1) +'.jpg'); cy(index); } }); // 定时任务 setInterval(function () { var sum = Math.floor(Math.random()*3)+1; img.attr('src','static/images/banner'+ sum +'.jpg'); cy(sum-1); },2000); // 设置激活按钮的样式 function cy(ele) { lis.each(function (index) { if (ele === index){ $(this).css({'color':'black','background-color':'white'}) }else { $(this).css({'color':'white','background-color':'black'}) } }); } }); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例