原生JS实现简单的轮播图
注意
我们用原生JS来做一个简单的无缝轮播图,首先需要准备几张图片作为材料,图片的链接需要自己设置,所以这边我的代码中图片链接的位置请大家自己添加图片。
代码
我这边用的是面向对象的写法来做的轮播图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>轮播图</title>
<style>
* {
margin: 0;
padding: 0;
}
#cont {
position: absolute;
left: 0;
}
#cont img {
width: 400px;
height: 300px;
float: left;
}
.box {
overflow: hidden;
width: 400px;
height: 300px;
position: relative;
margin: 10px auto;
}
#left {
position: absolute;
width: 60px;
height: 60px;
background: #ccc;
opacity: .5;
border: 0;
left: 0;
top: 103px;
}
#right {
position: absolute;
width: 60px;
height: 60px;
background: #ccc;
opacity: .5;
border: 0;
right: 0;
top: 103px;
}
</style>
</head>
<body>
<div class="box">
<div id="cont">
<img src="images/bg1.jpg" alt="">
<img src="images/bg2.jpg" alt="">
<img src="images/bg3.jpg" alt="">
<img src="images/bg4.jpg" alt="">
<img src="images/bg5.jpg" alt="">
<img src="images/bg1.jpg" alt=""> <!-- 这里注意要加一个图片达到无缝切换 -->
</div>
<div id="btn">
<input type="button" id="left" value="<<<">
<input type="button" id="right" value=">>>">
</div>
</div>
</body>
<script src="../../../move.js"></script>
<script>
function Top() {
this.cont = document.getElementById("cont");
this.aimg = this.cont.children;
this.left = document.getElementById("left");
this.right = document.getElementById("right");
this.cont.style.width = this.aimg.length * this.aimg[0].offsetWidth + "px";
this.index = 0;
this.init();
}
Top.prototype.init = function () {
//绑定事件
var that = this;
this.right.onclick = function () {
that.rightChange();
}
this.left.onclick = function () {
that.leftChange();
}
}
Top.prototype.leftChange = function () {
//左边的按钮判定,在如果索引在0的时候点击会跳到第五张1,由于最后一张为图片1,所以length-2
if (this.index == 0) {
this.index = this.aimg.length - 2;
this.cont.style.left = -(this.aimg.length - 1) * this.aimg[0].offsetWidth + "px";
console.log(this.index * this.aimg[1].offsetWidth);
} else {
this.index--;
}
this.dispaly()
}
Top.prototype.rightChange = function () {
//计算索引
if (this.index == this.aimg.length - 1) {
this.index = 1;
this.cont.style.left = 0;
} else {
this.index++;
}
this.dispaly()
}
Top.prototype.dispaly = function () {
//这里
move(this.cont, {
left: -this.index * this.aimg[1].offsetWidth
})
}
//下面为调用的两个函数,主要是用来做动画效果
function move(ele,json,callback){
clearInterval(ele.t);
ele.t = setInterval(() => {
var onoff = true;
for(var i in json){
var iNow = parseInt(getStyle(ele,i));
var speed = (json[i] - iNow)/6;
speed = speed<0 ? Math.floor(speed) : Math.ceil(speed);
if(iNow != json[i]){
onoff = false;
}
ele.style[i] = iNow + speed + "px";
}
if(onoff){
clearInterval(ele.t);
callback && callback();
}
}, 30);
}
function getStyle(ele,attr){
if(ele.currentStyle){
return ele.currentStyle[attr];
}else{
return getComputedStyle(ele,false)[attr];
}
}
//执行代码,需要放到最后执行
new Top();
</script>
</html>
还没有评论,来说两句吧...