HTML代码块:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>图片轮播</title>
6 <link href="carousel.css" rel="stylesheet" type="text/css">
7 </head>
8 <body>
9 <div class="outer">
10 <ul class="img">
11 <li><a href=""><img src="picture/cat.jpg" class="pic"></a></li>
12 <li><a href=""><img src="picture/dog.jpg" class="pic"></a></li>
13 <li><a href=""><img src="picture/mouse.jpg" class="pic"></a></li>
14 <li><a href=""><img src="picture/qie.jpg" class="pic"></a></li>
15 <li><a href=""><img src="picture/tun.jpg" class="pic"></a></li>
16 <li><a href=""><img src="picture/xiniu.jpg" class="pic"></a></li>
17
18 </ul>
19
20 <ul class="num">
21
22 </ul>
23
24 <div class="left btn"> < </div>
25 <div class="right btn"> > </div>
26 </div>
27
28
29 <script src="jquery-3.3.1.min.js"></script>
30 <script src="carousel.js"></script>
31 </body>
32 </html>
css代码块:
1 .outer{
2 650px;
3 height: 407px;
4 margin: 80px auto;
5 position: relative;
6 }
7 .img li{
8
9 position: absolute;
10 list-style: none;
11 top:0;
12 left: 0;
13 }
14 .pic{
15 100%;
16 height: 100%;
17 }
18 .num{
19 position: absolute;
20 bottom: 10px;
21 left: 200px;
22 list-style: none;
23 }
24 .num li{
25 display: inline-block;
26 18px;
27 height: 18px;
28 background-color: white;
29 text-align: center;
30 border-radius: 50%;
31 line-height: 18px;
32 margin-left: 10px;
33 }
34 .btn{
35 position: absolute;
36 top:50%;
37 30px;
38 height: 60px;
39 background-color: lightgray;
40 color: white;
41 text-align: center;
42 line-height: 60px;
43 font-size: 30px;
44 opacity: 0.5;
45 margin-top: -30px;
46 display: none;
47 }
48 .outer:hover .btn{
49 display: block;
50 }
51 .num li.active{
52 background-color: red;
53 }
54
55 .left{
56 left: 0;
57 }
58 .right{
59 right: 0;
60 }
JavaScript代码块:
1 var x=0;
2 //通过jQuery来创建图片标签
3 var img_num=$(".img li").length;
4 for(var i=0;i<img_num;i++){
5 $(".num").append("<li></li>")
6 }
7 $(".num li").eq(0).addClass("active");
8
9 //鼠标悬浮手动轮播
10 $(".num li").mouseover(function () {
11 x=$(this).index();
12 $(this).addClass("active").siblings().removeClass("active");
13 $(".img li").eq(x).stop().fadeIn(200).siblings().stop().fadeOut(200);
14 });
15 //自动轮播
16 var c=setInterval(go_r,2000);
17
18 function go_r() {
19 if(x==img_num-1){
20 x=-1;
21 }
22 x++;
23 $(".num li").eq(x).addClass("active").siblings().removeClass("active");
24 $(".img li").eq(x).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
25
26 }
27 function go_l() {
28 if(x==0){
29 x=img_num;
30 }
31 x--;
32 $(".num li").eq(x).addClass("active").siblings().removeClass("active");
33 $(".img li").eq(x).stop().fadeIn(1000).siblings().stop().fadeOut(1000);
34 }
35 //鼠标悬浮停止
36 $(".outer").hover(function () {
37 clearInterval(c)
38 },function () {
39 c=setInterval(go_r,2000)
40 });
41 //鼠标切换图片
42 $(".right").click(go_r);
43 $(".left").click(go_l);