Js实现图片点击切换与轮播
时间: 2023-06-17 19:06:42 浏览: 133
图片点击切换:
HTML结构:
```html
<div class="image-container">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
```
CSS样式:
```css
.image-container {
display: flex;
justify-content: center;
}
.image-container img {
width: 200px;
height: 200px;
margin: 0 10px;
cursor: pointer;
}
```
JavaScript代码:
```javascript
const images = document.querySelectorAll('.image-container img');
let currentImage = 0;
// 显示当前选中的图片
function showImage() {
images.forEach(image => image.classList.remove('active'));
images[currentImage].classList.add('active');
}
// 点击图片时切换图片
images.forEach((image, index) => {
image.addEventListener('click', () => {
currentImage = index;
showImage();
});
});
// 显示下一张图片
function nextImage() {
currentImage++;
if (currentImage >= images.length) {
currentImage = 0;
}
showImage();
}
// 每隔 5 秒自动切换图片
setInterval(() => {
nextImage();
}, 5000);
```
轮播:
HTML结构:
```html
<div class="slider-container">
<div class="slider-images">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button class="slider-button prev-button">Prev</button>
<button class="slider-button next-button">Next</button>
</div>
```
CSS样式:
```css
.slider-container {
position: relative;
}
.slider-images {
display: flex;
overflow: hidden;
}
.slider-images img {
width: 100%;
height: 100%;
}
.slider-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
background-color: #fff;
border: 1px solid #000;
cursor: pointer;
}
.prev-button {
left: 10px;
}
.next-button {
right: 10px;
}
```
JavaScript代码:
```javascript
const sliderImages = document.querySelector('.slider-images');
const prevButton = document.querySelector('.prev-button');
const nextButton = document.querySelector('.next-button');
let currentSlide = 0;
// 设置图片容器的宽度
function setSliderWidth() {
const numSlides = sliderImages.children.length;
sliderImages.style.width = `${numSlides * 100}%`;
}
// 设置每个幻灯片的宽度
function setSlideWidth() {
const slideWidth = `${100 / sliderImages.children.length}%`;
Array.from(sliderImages.children).forEach(slide => {
slide.style.width = slideWidth;
});
}
// 显示当前幻灯片
function showSlide() {
const slideWidth = parseInt(window.getComputedStyle(sliderImages.children[0]).width, 10);
const offset = -1 * currentSlide * slideWidth;
sliderImages.style.transform = `translateX(${offset}px)`;
}
// 显示下一个幻灯片
function nextSlide() {
currentSlide++;
if (currentSlide >= sliderImages.children.length) {
currentSlide = 0;
}
showSlide();
}
// 显示上一个幻灯片
function prevSlide() {
currentSlide--;
if (currentSlide < 0) {
currentSlide = sliderImages.children.length - 1;
}
showSlide();
}
// 设置幻灯片容器和幻灯片的宽度
setSliderWidth();
setSlideWidth();
// 点击按钮切换幻灯片
prevButton.addEventListener('click', prevSlide);
nextButton.addEventListener('click', nextSlide);
// 每隔 5 秒自动切换幻灯片
setInterval(() => {
nextSlide();
}, 5000);
```
阅读全文