css
* {
margin: 0;
padding: 0;
}
.myBox {
width: 600px;
height: 300px;
border: 1px solid #ccc;
overflow: hidden;
position: relative;
}
.container {
width: 100%;
height: 100%;
display: flex;
transition: all 1s;
}
.item {
width: 600px;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 1;
opacity: 0;
/* flex-shrink: 0; */
}
.item:nth-of-type(1) {
background-color: red;
}
.item:nth-of-type(2) {
background-color: rgb(13, 255, 0);
}
.item:nth-of-type(3) {
background-color: rgb(47, 0, 255);
}
.item:nth-of-type(4) {
background-color: rgb(255, 0, 123);
}
.item.active {
opacity: 1;
}
.icon {
width: 220px;
height: 40px;
position: absolute;
z-index: 3;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
justify-content: space-around;
align-items: center;
}
.icon span {
width: 34px;
height: 34px;
border: 1px solid #ccc;
border-radius: 50%;
cursor: pointer;
}
span.active {
background: #ccc;
}
html和 js
<div class="myBox">
<div class="container">
<div class="item active">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div class="icon">
<span class="active"></span><span></span><span></span><span></span>
</div>
</div>
<script>
const doms = {
activeIndex:0,//当前选中的图片索引
carousel: document.querySelector('.container'),// 横向轮播
items: document.querySelectorAll('.container .item'),
indicators: document.querySelectorAll('.icon span')//导航图标
}
setInterval(() => {
if (doms.activeIndex > 3) {
doms.activeIndex = 0;
}
// translateMoveTo(doms.activeIndex)
ZindexMoveTo(doms.activeIndex)
doms.activeIndex++;
}, 1000)
// 图片左右轮播方法
const translateMoveTo = (num) => {
const translateNum = -600 * num;
doms.carousel.style.transform = `translateX(${translateNum}px)`;
changeIconActive(num);
}
// 图片渐隐渐显方法
const ZindexMoveTo = (num) => {
doms.items.forEach((item, i) => {
item.style.opacity = 0;
})
doms.items[num].style.opacity = 1;
changeIconActive(num);
}
// 导航图标样式切换
const changeIconActive = (num)=>{
const active = document.querySelector('.icon span.active');
if (active) {
active.classList.remove('active');
}
doms.indicators[num].classList.add('active');
}
// 点击导航图标切换图片
doms.indicators.forEach((item, i) => {
item.onclick = () => {
doms.activeIndex = i;
// translateMoveTo(i);
ZindexMoveTo(i);
}
})
</script>