效果:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="out-container">
<div class="inner-container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div class="tools">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
CSS:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.out-container{
width: 500px;
height: 400px;
margin: auto;
overflow: hidden;
position: relative;
}
.inner-container{
width: 100%;
height: 100%;
display: flex;
transition: all 0.5s;
}
.tools{
position: absolute;
left: 50%;
bottom: 10px;
transform: translateX(-50%);
display: flex;
}
.tools>span{
width: 20px;
height: 20px;
margin: 0 5px;
border-radius: 20px;
background: #ffffff;
outline: #ffffff;
}
.tools>span.active{
background: greenyellow;
}
.item{
flex: 0 0 auto; /* 不改变宽度,保持内容宽度 */
width: 500px;
height: 400px;
}
.item:nth-child(1){
background-color: rgb(192, 255, 207);
}
.item:nth-child(2){
background-color: rgb(192, 224, 255);
}
.item:nth-child(3){
background-color: rgb(255, 192, 236);
}
.item:nth-child(4){
background-color: rgb(250, 255, 192);
}
JS:
const innerContainer = document.querySelector('.inner-container')
let itemCount = innerContainer.childElementCount
const toolItems = document.querySelectorAll('.tools span')
toolItems.forEach((item,index)=>{
item.addEventListener('click',()=>{
move(index)
})
})
function move(index){
toolItems.forEach(item=>item.classList.remove('active'))
toolItems[index].classList.add('active')
if(index == itemCount)index = 0
innerContainer.style.transform = `translateX(${-100 * index}%)`
}