js图片轮播图和点击切换
时间: 2024-05-15 16:18:40 浏览: 15
您好,实现图片轮播和点击切换的方式有很多种,以下是其中一种基于 JavaScript/jQuery 的示例代码:
HTML 结构:
```html
<div class="slider">
<img src="img1.jpg" alt="Image 1">
<img src="img2.jpg" alt="Image 2">
<img src="img3.jpg" alt="Image 3">
</div>
<div class="buttons">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
```
CSS 样式:
```css
.slider {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
.slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-out;
}
.slider img.active {
opacity: 1;
}
.buttons {
margin-top: 10px;
}
```
JavaScript/jQuery 代码:
```js
$(document).ready(function() {
var $slider = $('.slider');
var $slides = $slider.find('img');
var $prevBtn = $('.prev');
var $nextBtn = $('.next');
var currentIndex = 0;
function showSlide(index) {
$slides.removeClass('active');
$slides.eq(index).addClass('active');
}
function prevSlide() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = $slides.length - 1;
}
showSlide(currentIndex);
}
function nextSlide() {
currentIndex++;
if (currentIndex >= $slides.length) {
currentIndex = 0;
}
showSlide(currentIndex);
}
$prevBtn.on('click', prevSlide);
$nextBtn.on('click', nextSlide);
// Show the first slide
showSlide(currentIndex);
});
```
这段代码实现了一个基本的轮播图,通过点击 "Prev" 和 "Next" 按钮切换图片。其中,`.slider` 是轮播图容器,`.slider img` 是图片元素,`.buttons` 是按钮容器,`.prev` 和 `.next` 是切换按钮。具体实现过程见代码注释。