轮播图:
接触jquery也有一段时间了,今天刚好利用轮播图来练练手。博文的前面会介绍一个简单用jquery做轮播图的例子,中间会插入一些关于轮播图更多的思考,在后面会用Javascript的方法来写一个轮播图,最后则是关于jquery和Javascript的比较。
jquery做轮播图的例子:
html部分代码:
css部分代码:
- {
margin: 0;
padding: 0;
} - {
margin: 0;
padding: 0;
}
#igs {
margin: 10px auto;
width: 700px;
height: 320px;
position: relative;
}
.ig {
position: absolute;
}
#tabs {
position: absolute;
list-style: none;
background-color: rgba(255,255,255,.5);
left: 300px;
bottom: 10px;
border-radius: 10px;
padding: 5px 0 5px 5px;
}
.tab{
float: left;
text-align: center;
line-height: 20px;
width: 20px;
height: 20px;
cursor: pointer;
overflow: hidden;
margin-right: 4px;
border-radius: 100%;
background-color: rgb(200,100,150);
}
.btn{
position: absolute;
color: #fff;
top: 110px;
width: 40px;
height: 100px;
background-color: rgba(255,255,255,.3);
font-size: 40px;
font-weight: bold;
text-align: center;
line-height: 100px;
border-radius: 5px;
margin: 0 5px;
}
.btn2{
position: absolute;
right: 0px;
}
.btn:hover{
background-color: rgba(0,0,0,.7);
}
js部分代码:
//定义全局变量和定时器
var i = 0 ;
var timer;
$(document).ready(function(){
//用jquery方法设置第一张图片显示,其余隐藏
$(’.ig’).eq(0).show().siblings(’.ig’).hide();
//调用showTime()函数(轮播函数)
showTime();
//当鼠标经过下面的数字时,触发两个事件(鼠标悬停和鼠标离开)
$(’.tab’).hover(function(){
//获取当前i的值,并显示,同时还要清除定时器
i = $(this).index();
Show();
clearInterval(timer);
},function(){
//
showTime();
});
//鼠标点击左侧的箭头
$(’.btn1’).click(function(){
clearInterval(timer);
if(i == 0){
i = 5;//注意此时i的值
}
i–;
Show();
showTime();
});
//鼠标点击右侧的箭头
$(’.btn2’).click(function(){
clearInterval(timer);
if(i == 4){
i = -1;//注意此时i的值
}
i++;
Show();
showTime();
});
});
//创建一个showTime函数
function showTime(){
//定时器
timer = setInterval(function(){
//调用一个Show()函数
Show();
i++;
//当图片是最后一张的后面时,设置图片为第一张
if(i==5){
i=0;
}
},2000);
}
//创建一个Show函数
function Show(){
//在这里可以用其他jquery的动画
$(’.ig’).eq(i).fadeIn(300).siblings(’.ig’).fadeOut(300);
//给.tab创建一个新的Class为其添加一个新的样式,并且要在css代码中设置该样式
$(’.tab’).eq(i).addClass(‘bg’).siblings(’.tab’).removeClass(‘bg’);
/*
- css中添加的代码:
- .bg{ background-color: #f00; }
- */
}