我想我在js代码中犯了一个错误,因为当我点击时它不起作用。没有行动。我应该在js代码改变什么?js代码:
const slides = document.querySelector(".slides");
const slidesCount = slides.childElementCount;
console.log(slidesCount)
const nextBtn=document.querySelector(".next-slide");
const prevBtn=document.querySelector(".prev-slide");
const container = document.querySelector('.slider-container')
//Controls
prevBtn.addEventListener('click', () => {
changeSlide('prev')
})
nextBtn.addEventListener('click', () => {
changeSlide('next')
})
let activeSlideIndex = 0
function changeSlide(direction) {
if(direction === 'prev') {
activeSlideIndex++
if(activeSlideIndex === slidesCount) {
activeSlideIndex = 0
}
} else if(direction === 'next') {
activeSlideIndex--
if(activeSlideIndex < 0) {
activeSlideIndex = slidesCount - 1
}
}
}
这是我的html代码。
<button class="prev-slide">◁</button>
<button class="next-slide">▷</button>
</div>
<div class="slides">
<img class="slide" src="images/picture1.jpg" alt="slide image">
<img class="slide" src="images/picture2.jpg" alt="slide image">
<img class="slide" src="images/picture3.jpg" alt="slide image">
</div>
我认为唯一缺少的是实际的渲染。你必须以某种方式隐藏或显示活动幻灯片。我通过添加active
类并只显示它(通过CSS)来做到这一点。然后,您的changeSlide函数不仅计算活动幻灯片,而且还在适当的元素上设置类。
const slides = document.querySelector(".slides");
const slidesCount = slides.childElementCount;
console.log(`Showing ${slidesCount} slides.`)
const nextBtn=document.querySelector(".next-slide");
const prevBtn=document.querySelector(".prev-slide");
const container = document.querySelector('.slider-container')
//Controls
prevBtn.addEventListener('click', () => {
changeSlide('prev')
})
nextBtn.addEventListener('click', () => {
changeSlide('next')
})
let activeSlideIndex = 0
function changeSlide(direction) {
if(direction === 'prev') {
activeSlideIndex++
if(activeSlideIndex === slidesCount) {
activeSlideIndex = 0
}
} else if(direction === 'next') {
activeSlideIndex--
if(activeSlideIndex < 0) {
activeSlideIndex = slidesCount - 1
}
}
Array.from(slides.children).forEach((slide, idx) => {
if (idx === activeSlideIndex) {
slide.classList.add('active');
} else {
slide.classList.remove('active');
}
});
}
.controls {
margin-bottom: 2em;
}
.slides .slide {
display: none
}
.slides .slide.active {
display: block;
}
<section class="controls">
<button class="prev-slide">◁</button>
<button class="next-slide">▷</button>
</section>
<div class="slides">
<img class="slide active" src="https://via.placeholder.com/450x250" alt="slide image">
<img class="slide" src="https://loremflickr.com/640/250" alt="slide image">
<img class="slide" src="https://www.fillmurray.com/640/250" alt="slide image">
</div>