随着前端框架的不断增多,我们需要写的功能也越来越少,很多情况下我都能够找到大量轮播图UI插件,甚至比我们写的都要漂亮和强大,但是如果你是js刚入门的小白,你就需要从原生JS开始学习,那么轮播图就是你必须要知道的,本文只是众多轮播图方法中的一个,目的是让你了解轮播图的运行原理,具体JS代码如下:
var aSpan = dot.getElementsByTagName('span'); //小圆点
var aBtn = btn.getElementsByTagName('span'); // 左右按钮
var aLi = list.getElementsByTagName('li'); //存放图片的li
//小圆点
var num = 0;
var conut = 0;
var nowTime = 0;
aSpan[num].className = 'on';
for (var i=0;i<aSpan.length;i++ )
{
aSpan[i].index = i;
aSpan[i].onclick = function(){
for (var i=0;i<aSpan.length;i++ )
{
aSpan[i].className = '';
}
num = this.index;
conut = this.index;
this.className = 'on';
move( list , {top:-284*this.index} , 1000 , 'bounceOut' );
};
};
//根据索引值来判断左右按钮
for ( var i=0;i<aBtn.length;i++ )
{
aBtn[i].xyz = i;
aBtn[i].onclick = function(){
if ( new Date() - nowTime > 1100 )
{
nowTime = new Date();
if( this.xyz ){ //右按钮
play();
}else{ // 左按钮
if ( num == 0 ){
// 让最后一li移到第一的位置上
aLi[4].style.position = 'relative';
aLi[4].style.top = -284*aSpan.length + 'px';
num = aSpan.length-1;
}else{
num--;
};
// 小圆点
for (var i=0;i<aSpan.length;i++ ) // 小圆点
{
aSpan[i].className = '';
};
aSpan[num].className = 'on';
conut--;
move( list , {top:-284*conut} , 1000 , 'bounceOut' , function(){
if ( num == aSpan.length-1 )
{
list.style.top = -284 *(aSpan.length-1) + 'px';
aLi[4].style.position = 'static';
conut = aSpan.length-1;
}
} );
};
}
};
};
var timer = setInterval(play,2500);
banner.onmouseover = function(){
clearInterval(timer);
};
banner.onmouseout = function(){
timer = setInterval(play,2500);
};
function play(){
if ( num == aSpan.length-1 ) // 先判断
{
// 把第一个li放到最后的位置上
aLi[0].style.position = 'relative';
aLi[0].style.top = 284*aSpan.length + 'px';
num=0;
}else{
num++;
};
for (var i=0;i<aSpan.length;i++ ) // 小圆点
{
aSpan[i].className = '';
};
aSpan[num].className = 'on';
conut ++; // conut 来控制 list运动
move( list , {top:-284*conut} , 1000 , 'bounceOut' , function(){
if( num == 0)
{
aLi[0].style.position = 'static';
list.style.top = 0; // 让ul 的top =0
conut = 0;
}
} );
};