用js设计程序,给你若干张图片,通过单击上一张,下一张按钮实现图片的动态循环显示。如果没单击按钮,则每3秒钟自动循环显示下一张图片完整代码
时间: 2024-05-15 11:17:57 浏览: 10
首先,我们需要一个数组来存储图片的地址:
```
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
```
然后,我们需要一个变量来存储当前显示的图片的索引:
```
var currentImageIndex = 0;
```
接下来,我们需要编写一个函数来修改图片的src属性,实现图片的动态循环显示:
```
function showImage() {
var imageElement = document.getElementById('image');
imageElement.src = images[currentImageIndex];
currentImageIndex++;
if (currentImageIndex >= images.length) {
currentImageIndex = 0;
}
setTimeout(showImage, 3000);
}
```
这个函数首先获取图片元素,修改它的src属性为当前索引对应的图片地址,然后将当前索引加1。如果当前索引已经超出了数组的长度,则将它重置为0。最后,通过setTimeout函数每隔3秒钟调用一次这个函数,实现自动循环显示下一张图片。
最后,我们只需要在HTML中添加一个图片元素和两个按钮,绑定它们的click事件,调用showImage函数即可:
```
<img id="image" src="image1.jpg">
<button onclick="currentImageIndex--; if (currentImageIndex < 0) {currentImageIndex = images.length - 1;} showImage();">上一张</button>
<button onclick="showImage();">下一张</button>
<script>
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var currentImageIndex = 0;
function showImage() {
var imageElement = document.getElementById('image');
imageElement.src = images[currentImageIndex];
currentImageIndex++;
if (currentImageIndex >= images.length) {
currentImageIndex = 0;
}
setTimeout(showImage, 3000);
}
showImage();
</script>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)