粗糙简易版轮播图
实现效果
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播</title>
<style>
*{
box-sizing: border-box;
}
body{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.viewContainer{
width: 690px;
height: 1267px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.imgs{
display: flex;
transform: translateX(0);
transition: transform 0.5s ease-in-out;
}
.buttons{
display: flex;
height: 40px;
}
.buttons >button{
height: 100%;
width: 48%;
background-color: #2A86BA;
border: 1px solid #777777;
border-radius: 3px;
}
.pre{
margin: 0 15px 0 0;
}
.next{
margin: 0 0 0 15px;
}
</style>
</head>
<body>
<div class="viewContainer">
<div class="imgs">
<img src="../images/sunsets3.jpg">
<img src="../images/sunsets2.jpg">
<img src="../images/sunset1.jpg">
<img src="../images/sunsets0.jpg">
</div>
<div class="buttons">
<button class="pre">上一个</button>
<button class="next">下一个</button>
</div>
</div>
<script>
const imgs=document.querySelector('.imgs');
const pre=document.querySelector('.pre');
const next=document.querySelector('.next');
let index=0;
function run() {
index++;
changeImg();
}
function changeImg() {
imgs.style.transform=`translateX(${-(index%4)*690}px)`;
}
let timer=setInterval(run,2000);
function resetTimer(){
clearInterval(timer);
timer=setInterval(run,2000);
}
pre.addEventListener('click',function () {
index--;
changeImg();
resetTimer();
})
next.addEventListener('click',function () {
index++;
changeImg();
resetTimer();
})
</script>
</body>
</html>
终于熟练背写轮播图了,主要是想熟悉css里的属性。
上次看到一个比较好看精致的轮播图,下次实现精致的轮播图。