一、原理
- 给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记录