具体代码写在一起
时间: 2024-02-29 07:52:51 浏览: 24
好的,以下是具体的代码实现:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>随机显示图片</title>
<script src="randomImage.js"></script>
</head>
<body onload="randomImage()">
<h1>随机显示图片</h1>
<img id="random-img" src="">
<button onclick="randomImage()">随机显示图片</button>
</body>
</html>
```
JavaScript代码(保存为randomImage.js文件):
```
var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"];
function randomImage() {
var randomIndex = Math.floor(Math.random() * images.length);
var img = document.getElementById("random-img");
img.src = images[randomIndex];
}
```
上述代码中,HTML中的`<img>`标签的src属性初始值为空,JavaScript中的`randomImage`函数在页面加载时随机选择一个图片文件名,并将其设置为`<img>`标签的src属性。同时,HTML中的按钮绑定了该函数,当用户点击按钮时也会随机显示一张图片。
相关推荐
![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)