简单的轮播JS插件

一、原理

  • 给img设置绝对定位,令他们重叠在一起。
  • 利用css的z-index属性
  • 定时器——>当定时器切换时,给后面的图片添加z-index,且值比上一个大于1。这样就能显示图片了。

二、JS封装模板

 忘记在哪里看到的模板......

//匿名函数,防止变量污染
;(function(global){
	//构造函数,使用new使用
	function Swiper(el,option){
		
	};
	//原型上提供方法和属性
	Swiper.prototype={		
		
	};
	if (typeof module !== 'undefined' && module.exports) { //CommonJs规范 
        module.exports = Swiper;
    }else if (typeof define === 'function'){ //AMD/CMD规范
        define(function () {
            return Swiper
        })
    }else { //global指向this,this在插件外指向window.可以直接使用script标签
        global.Swiper = Swiper;
    }
})(this)

三、 模板运用

//swiper.js文件
//匿名函数,防止变量污染
;(function(global){
	//构造函数,使用new使用
	function Swiper(el,option){
		this.speed=option.speed||3000
		this.timer=null
		this.imgs=el
		this.active()
	};
	//原型上提供方法和属性
	Swiper.prototype={		
		constructor:Swiper,
		active:function(){
			var that=this
			//给图片添加zindex来显示				
			let num=0;
	 		let len=imgs.length-1;
	 		let index=1;
 			that.timer=setInterval(function(){					 								
 				if(num>len){num=0}
 				imgs[num].style.zIndex=index++;		
 				num++;
 			}, that.speed);	
		},
		stop:function(){
			var that=this
			clearInterval(that.timer)
			console.log('定时器停止')
		}
	};
	if (typeof module !== 'undefined' && module.exports) { //CommonJs规范 
        module.exports = Swiper;
    }else if (typeof define === 'function'){ //AMD/CMD规范
        define(function () {
            return Swiper
        })
    }else { //global指向this,this在插件外指向window.可以直接使用script标签
        global.Swiper = Swiper;
    }
})(this)

四、使用JS

样式随手写的。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="swiper.js" ></script>
		<style>
			.imgs{											
				height: 400px;
				top: 100px;
				left: 50%;
				width: 400px;
				margin: 0 auto;
			}
			img{
				width: 400px;
				height: 400px;
				position: absolute;
						
			}
			button{
				position:relative;
				z-index: 10000;
			}	
				
		</style>
	</head>
	<body>
		
		<div class="imgs">
			<img src="1.jpg"/>
			<img src="2.jpg" />
			<img src="3.jpg"/>
			<img src="4.jpg" />
			<button>stop</button>
			<button>start</button>
		</div>
		<script>
			var imgs=document.querySelectorAll('img')
			var btns=document.querySelectorAll('button')
			var config={
				'speed':2000
			}
			var swiper = new Swiper(imgs,config);
			//
			btns[0].onclick=function(){
				swiper.stop();
			}
			btns[1].onclick=function(){
				swiper.active();
			}
		</script>
	</body>
</html>

五、总结

也不知道使用z-index做轮播图,性能有没有问题~

2021-01-09记录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值