轮播图,是网站首页中常见的一种图片切换特效,作为前端开发者,我相信很多开发者都直接调用了jquery中的封装好的方法实现图片轮播,省事简单。所以我想介绍一下javascript纯代码实现的图片轮播。
HTML
1 2 3 4 5
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
1 2 3 4 5
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
- @@##@@
这里我相信最多疑惑的是,明明五张图片为何要在首尾加两张图片(li)做首尾呼应呢?原因如下图:
立即学习“Java免费学习笔记(深入)”;
这里以向左滚动的例子为说明
一开始布局的时候left: -470px;先处于第2个li也就是第2张图,当我们图片陆续向左滚动到第7张图片的时候,迅速扯回到第2张图,然后还是继续向左滚动。这样看起来就像是假象式的无限向左滚动循环,其实它里面只有7张图组成。同样的,如果实现向右滚动,我们一开始布局的时候,先处于第1个li也就是第1张图,当我们图片陆续向右滚动到第6张图片的时候,迅速扯回到第1张图,然后还是继续向右滚动。其实上下滚动轮播图道理是一样的,只不过少了一个float:left属性,让li垂直排列。
CSS
*{
margin: 0;
padding: 0;
list-style: none;
}
span{
width: 20px;
height: 20px;
display: block;
background-color: blanchedalmond;
border: 1px solid black;
float: left;
text-align: center;
line-height: 20px;
z-index: 1;
cursor: pointer;
margin: 120px 8px 0 0;
}
span.mouseover{
background-color: orange;
}
#content_img1{
position: relative;
width: 470px;
height: 150px;
border: 2px black solid;
margin: 30px auto;
overflow: hidden;
}
#img1{
position: absolute;
top: 0px;
left: -470px;
z-index: -1;
width: 700%;
height: 150px;
}
#img1>li{
width: 470px;
height: 150px;
float: left;
}
#content_img2{
position: relative;
width: 470px;
height: 150px;
border: 2px black solid;
margin: 30px auto;
overflow: hidden;
}
#img2{
position: absolute;
top: -150px;
left: 0px;
z-index: -1;
width: 470px;
height: 700%;
}
#img2>li{
width: 470px;
height: 150px;
}
javascript函数方法
window.onload=function(){
var cont_img1=document.getElementById("content_img1");
var spannum1=cont_img1.getElementsByTagName("span");
var img1=document.getElementById("img1");
var cont_img2=document.getElementById("content_img2");
var spannum2=cont_img2.getElementsByTagName("span");
var img2=document.getElementById("img2");
//向左轮播图的span"按钮"鼠标经过事件
for(var i=0;i0?Math.ceil(speed):Math.floor(speed);
if(speed==0){
clearInterval(obj.timer);
if(continuefunction) continuefunction();
}else{
obj.style[stylename]=(offvalue+speed)/100;
obj.style.filter="alpha(opacity:"+(offvalue+speed)+")";
}
}else{
var offvalue=parseInt(getStyle(obj,stylename));
var speed=(target-offvalue)/average;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(speed==0){
clearInterval(obj.timer);
if(continuefunction) continuefunction();
}else{
obj.style[stylename]=offvalue+speed+"px";
}
}
},cycle);
}
function getStyle(obj,stylename){//对象样式属性大小获取函数
if(obj.currentStyle){
return obj.currentStyle[stylename];
}else if(getComputedStyle(obj,false)){
return getComputedStyle(obj,false)[stylename];
}
}
这种通过计算位置轮播算法的好处是,可以在我的样式范围内,在HTML的











