原生JavaScript实现无缝轮播图完整代码

作者:拾光时间:2026-10-23 16:23:05浏览:438

本文提供使用原生JavaScript实现无缝轮播图的完整解决方案。涵盖HTML结构搭建、CSS样式布局以及核心JS逻辑,包括图片容器宽度计算、左右按钮点击事件处理及平滑移动动画函数。代码包含首尾图片复制技巧以实现视觉无缝循环,适合前端初学者参考学习。

原生JavaScript无缝轮播图实现

本文展示了一个使用原生JavaScript实现的轮播图实例,提供完整的代码示例供开发者参考和直接使用。

首先定义轮播图的CSS样式,设置容器尺寸、图片排列方式及控制按钮的绝对定位。

CSS样式定义


<style type="text/css">
 #box{width: 1000px;height: 375px;border: 3px solid black;
 margin: 30px auto;position: relative;overflow: hidden;}
 #box .img{position: absolute;left: 0;top: 0;}
 #box .img img{width: 1000px;height: 375px;float: left;}
 #box .btn input{border-radius: 50%;border: 0;width: 40px;
 height: 40px;font-size: 25px;z-index: 5;top: 165px;position: absolute;}
 #left{left: 0;}
 #right{right: 0;}
</style>

接着构建HTML结构,包含图片容器、导航按钮以及用于实现无缝效果的冗余图片元素。

HTML结构搭建


<div id="box">
 <div class="img">
 <img src="img/1.jpg" >
 <img src="img/2.jpg" >
 <img src="img/3.jpg" >
 <img src="img/4.jpg" >
 <img src="img/1.jpg" > //利用第一张图,达到无缝轮播的视觉效果
 </div>
 <div class="btn">
 <input type="button" id="left" value="<" />
 <input type="button" id="right" value=">" />
 </div>
</div>

编写JavaScript类来初始化轮播图,获取DOM元素、计算容器总宽度并绑定事件监听器。

JavaScript核心逻辑


<script>
 class LunBO{
 constructor() {
  this.img = document.querySelector(".img");
 this.child = this.img.children;
 this.left = document.getElementById("left");
 this.right = document.getElementById("right");
 this.index = 0;
 }
 init(){
 this.img.style.width = this.child.length * this.child[0].offsetWidth + "px"; //有多少图片设置多少宽度
 }
 addEvent(){
 var that = this;
 this.left.onclick = function(){
 that.changeIndex(1); //点击左按钮,设置索引
 }
 this.right.onclick = function(){
 that.changeIndex(2); //点击右按钮,设置索引
 }
 }
 changeIndex(i){
 if(i==1){
 if(this.index == 0){
  this.index = this.child.length - 2;
  this.img.style.left = -(this.child.length-1) * this.child[0].offsetWidth + "px";
 }else{
  this.index--;
 }
 }else{
 if(this.index == this.child.length-1){
  this.index = 1;
  this.img.style.left = 0;
 }else{
  this.index++;
 }
 }
 this.setSplace();
 }
 setSplace(){
 move(this.img,"left",-this.index * this.child[0].offsetWidth); //调用动画
 }
 }
 var lb = new LunBO();
 lb.init();
 lb.addEvent();
</script>

实现平滑移动动画函数,通过定时器逐步改变图片位置或透明度,确保切换过程流畅自然。

动画与工具函数


function move(ele,attr,target){
 clearInterval(ele.t);
 ele.t=setInterval(()=>{
 let iNow;
 if(attr=="opacity"){
 iNow=getStyle(ele,attr)*100;
 }else{
 iNow=parseInt(getStyle(ele,attr));
 }
 let speed=(target-iNow)/8;
 speed=speed<0?Math.floor(speed):Math.ceil(speed);
 if(iNow==target){
 clearInterval(ele.t);
 }else{
 if(attr=="opacity"){
 ele.style.opacity=(iNow+speed)/100;
 }else{
 ele.style[attr]=iNow+speed+"px";
 }
 }
 },30)
}
function getStyle(ele,attr){
 if(ele.currentStyle){
 return ele.currentStyle[attr];
 }else{
 return getComputedStyle(ele,false)[attr];
 }
}

相关技术专题:jQuery图片轮播、JavaScript图片轮播、Bootstrap图片轮播

希望上述内容能对您的学习有所帮助,欢迎继续支持本站获取更多技术资源。

作者最新文章