<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0;
padding: 0;
}
#carousel{
position: relative;
width: 400px;
height: 266px;
border:1px solid #000;
margin: 50px auto;
overflow: hidden;
}
ul{
position: relative;
left:0;
list-style: none;
width: 6000px;
transition: left .5s ease 0s;
}
ul>li{
float: left;
}
#lbtn{
position: absolute;
width: 50px;
height: 50px;
background: blue;
border-radius: 50%;
left: 20px;
top:50%;
margin-top: -25px;
}
#rbtn{
position: absolute;
width: 50px;
height: 50px;
background: blue;
border-radius: 50%;
right: 20px;
top:50%;
margin-top: -25px;
}
</style>
</head>
<body>
<div id="carousel">
<ul id="list">
<li><img src="../imgs/gk1.jpg" alt=""></li>
<li><img src="../imgs/gk2.jpg" alt=""></li>
<li><img src="../imgs/gk3.jpg" alt=""></li>
</ul>
<a href="javascript:;"><div id="lbtn"></div></a>
<a href="javascript:;"><div id="rbtn"></div></a>
</div>
<script>
let list = document.getElementById("list")
//克隆第一张图片到最后面是为了过渡到第一张图片,过渡后再瞬间拉回到第1张
let clone = list.firstElementChild.cloneNode(true);
list.appendChild(clone)
let rbtn = document.getElementById("rbtn")
var idx = 0 //0表示第一张图片
var lock = true;
rbtn.onclick = function(){
if(!lock){
return
}
//关锁
lock = false
list.style.transition = "left .5s ease 0s"
idx++;
if(idx > 2){
//设置延时器,当过渡完成后就瞬间拉回到第一张图片
setTimeout(function(){
list.style.transition = "none"
list.style.left = 0
idx = 0
},500)
}
list.style.left = -400 * idx + 'px';
//开锁
setTimeout(function(){
lock = true
},500)
}
lbtn.onclick = function(){
if(!lock){
return
}
//关锁
lock = false
//如果当前图片是第一张,瞬间拉回到最后一张(克隆图)
if(idx == 0){
list.style.transition = "none";
list.style.left = 3 * -400 + 'px';
setTimeout(function(){
//拉回倒数第2张时,把过渡效果加上
list.style.transition = "left .5s ease 0s"
idx = 2
list.style.left = idx * -400 + 'px'
},0)
}else{
idx--;
list.style.left = -400 * idx + 'px';
}
//500毫秒后开锁
setTimeout(function(){
lock = true
},500)
}
</script>
</body>
</html>
轮播图
最新推荐文章于 2022-02-15 19:51:21 发布