用JS实现 放一张图片,左边右边各一按钮,点击左边上一张图片,右边就显示 下一张图片
时间: 2024-03-20 20:43:15 浏览: 20
好的,下面是一个简单的实现方案:
HTML代码:
```html
<div>
<img id="image" src="image1.jpg">
<button id="prevBtn">上一张</button>
<button id="nextBtn">下一张</button>
</div>
```
JS代码:
```javascript
// 获取元素
const image = document.getElementById('image');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
// 图片数组
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
// 当前图片索引
let currentIndex = 0;
// 点击上一张按钮
prevBtn.addEventListener('click', () => {
if (currentIndex > 0) {
currentIndex--;
image.src = images[currentIndex];
}
});
// 点击下一张按钮
nextBtn.addEventListener('click', () => {
if (currentIndex < images.length - 1) {
currentIndex++;
image.src = images[currentIndex];
}
});
```
这段代码中,我们首先获取了页面中的元素,包括图片元素和两个按钮。然后定义了一个图片数组和一个当前图片索引变量。
当点击上一张或下一张按钮时,我们会判断当前索引是否越界,如果没有越界则更新当前索引,并将图片元素的src属性修改为当前索引对应的图片路径。这样就实现了点击左侧按钮上一张图片,右侧就会显示下一张图片的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)