网络编程 
首页 > 网络编程 > 浏览文章

js实现无缝轮播图

(编辑:jimmy 日期: 2024/5/8 浏览:3 次 )

本文实例为大家分享了js实现轮播图的具体代码,供大家参考,具体内容如下

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结构:

<div id="box">
 <div class="img">
 <img src="/UploadFiles/2021-04-02/1.jpg">

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"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图片轮播

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:js实现无缝轮播图效果
下一篇:基于vue+echarts 数据可视化大屏展示的方法示例
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网