原生JS实现不添加图片的无缝轮播

本文介绍如何使用原生JavaScript实现轮播图效果,包括通过点击小圆点切换图片、左右按钮控制图片滚动及自动播放功能。此教程适合JavaScript初学者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随着前端框架的不断增多,我们需要写的功能也越来越少,很多情况下我都能够找到大量轮播图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;
}
} );
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值