<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="jQuery.js"></script> <style type="text/css"> body{ margin:0; padding:0; background-color: #eeeeee; } .slide-container{ width:500px; height:250px; margin:200px auto; background-color: red; position:relative; box-sizing: border-box; } .slide-main{ width:100%; height:220px; background-color: black; box-sizing: border-box; } .slide-dot{ width:100%; height:30px; box-sizing: border-box; background-color: blue; padding-top:5px; } .slide-dot>span{ cursor:pointer; height: 13px; width: 13px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .slide-index { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0; } .slide-img{ width:100%; height:100%; } .myslide{ position: relative; height:220px; display: none; } .slide-text{ box-sizing: border-box; color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; width: 100%; text-align: center; bottom:20px; } .slide-main>.active{ display: block; } .slide-dot>span.active ,.slide-dot>span:hover{ background-color: pink; } </style> </head> <body> <!--幻灯片--> <div class="slide-container"> <!--幻灯片图片区域--> <div class="slide-main"> <div class="myslide active"> <!--显示索引位置--> <div class="slide-index"></div> <img src="https://c.runoob.com/wp-content/uploads/2017/01/img_fjords_wide.jpg" alt="" class="slide-img"> <!--显示文本--> <div class="slide-text"> 今天天气很好1 </div> </div> <div class="myslide"> <!--显示索引位置--> <div class="slide-index"></div> <img src="https://c.runoob.com/wp-content/uploads/2017/01/img_fjords_wide.jpg" alt="" class="slide-img"> <!--显示文本--> <div class="slide-text"> 今天天气很好2 </div> </div> <div class="myslide"> <!--显示索引位置--> <div class="slide-index"></div> <img src="https://c.runoob.com/wp-content/uploads/2017/01/img_fjords_wide.jpg" alt="" class="slide-img"> <!--显示文本--> <div class="slide-text"> 今天天气很好3 </div> </div> </div> <!--幻灯片的圆点部分--> <div class="slide-dot" align="center"> <span class="active"></span> <span></span> <span></span> </div> </div> </body> <script type="text/javascript"> /* 这里统一命名为slide */ /*先获取myslide dom元素数组和dot中span元素数组 默认从第一个开始变化 在每一次的函数当中先俺不移除active类 根据当前索引添加active类名称*/ var myslides = document.getElementsByClassName("myslide"); var dot = document.getElementsByClassName("dot")[0]; var spans = document.getElementsByTagName("span"); var slideIndex = document.getElementsByClassName("slide-index"); var length = spans.length; var index = 0;//当前为第一个元素 function changeSlide(){ //说有元素去掉active for(var i=0;i<length;i++){ spans[i].className =spans[i].className.replace("active",""); myslides[i].className = myslides[i].className.replace("active",""); } console.log(index); myslides[index].className+=" active"; spans[index].className+=" active"; slideIndex[index].innerHTML = index+1+"/"+length; //判断是否超出 if(++index>=length){ index=0; } } setInterval(changeSlide, 2000); </script> </html>