最終實作界面如下:
頁面加載時,自動輪播,輪播滑鼠懸停在整個banner容器的時候,兩邊會顯示向左,向右按鈕,滑鼠懸停在中下方索引圓圈的上面,自動跳轉到相應的圖檔。
banner容器裡面包含了圖檔清單img,索引圓圈 num,還有按鈕兩個btn
<div class="banner">
<ul class="img">
<li><img src="image/1.jpg" alt=""/></li>
<li><img src="image/2.jpg" alt="" /></li>
<li><img src="image/3.jpg" alt="" /></li>
<li><img src="image/4.jpg" alt="" /></li>
</ul>
<ul class="num">
</ul>
<div class="btn btn_l"><</div>
<div class="btn btn_r">></div>
</div>
以下是CSS樣式表,直接拷貝,可看到效果,隻是沒有使用JS實作輪播事件而已,
<style type="text/css">
*{ padding:0px; margin:0px;list-style:none;}
.banner { width:500px; height:300px; margin:100px auto; border:1px solid #808080; position:relative; overflow:hidden;}
.banner .img{width:5000px; position:absolute; left:0px;top:0px;}
.banner .img img{width:500px; height:300px;}
.banner .img li{float:left;}
.banner .num { position:absolute; width:100%; bottom:10px; left:0px; text-align:center; font-size:0px;}
.banner .num li { width:10px; height:10px; background-color:#888; border-radius:50%;display:inline-block; margin:0px 3px; cursor:pointer;}
.banner .num li.on {background-color: #ff6a00;}
.banner .btn {width: 30px;height: 50px;background-color: #808080;opacity: 0.5; filter:alpha(opacity:0.5); position:absolute;top:50%; margin-top:-25px;
cursor:pointer;
text-align:center;
line-height:50px;
font-size:40px;
color:#fff;
font-family:"宋體";
display:none;
}
.banner .btn_l { left:0px;}
.banner .btn_r { right:0px;}
.banner:hover .btn { display:block;}
</style>
以下是JS各個事件的調用,使用前别忘記引用jquery檔案,我這裡引用的是 <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i = 0;
var clone = $(".banner .img li").first().clone();//克隆第一張圖檔
$(".banner .img").append(clone);//複制到清單最後
var size = $(".banner .img li").size();
for (var j = 0; j < size-1; j++) {
$(".banner .num").append("<li></li>");
}
$(".banner .num li").first().addClass("on");
/*自動輪播*/
var t = setInterval(function () { i++; move();},2000);
/*滑鼠懸停事件*/
$(".banner").hover(function () {
clearInterval(t);//滑鼠懸停時清除定時器
}, function () {
t = setInterval(function () { i++; move(); }, 2000); //滑鼠移出時清除定時器
});
/*滑鼠滑入原點事件*/
$(".banner .num li").hover(function () {
var index = $(this).index();//擷取目前索引值
i = index;
$(".banner .img").stop().animate({ left: -index * 500 }, 500);
$(this).addClass("on").siblings().removeClass("on");
});
/*向左按鈕*/
$(".banner .btn_l").click(function () {
i++;
move();
})
/*向右按鈕*/
$(".banner .btn_r").click(function () {
i--;
move();
})
/*移動事件*/
function move() {
if (i == size) {
$(".banner .img").css({ left: 0 });
i = 1;
}
if (i == -1) {
$(".banner .img").css({ left: -(size - 1) * 500 });
i = size - 2;
}
$(".banner .img").stop().animate({ left: -i * 500 }, 500);
if (i == size - 1) {
$(".banner .num li").eq(0).addClass("on").siblings().removeClass("on");
} else {
$(".banner .num li").eq(i).addClass("on").siblings().removeClass("on");
}
}
});
</script>
拷貝起來很友善即用。