用js写一个点击按钮随机切换背景图片
时间: 2024-05-05 14:18:40 浏览: 103
好的,以下是用JavaScript写的代码,可以实现点击按钮随机切换背景图片:
HTML代码:
```
<button id="changeBgBtn">点击切换背景图片</button>
```
JavaScript代码:
```
var bgList = ['bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg']; // 背景图片列表
var bgIndex = 0; // 当前背景图片的索引
var changeBgBtn = document.getElementById('changeBgBtn');
var body = document.getElementsByTagName('body')[0];
changeBgBtn.onclick = function() {
bgIndex = Math.floor(Math.random() * bgList.length); // 随机生成一个背景图片的索引
body.style.backgroundImage = 'url(' + bgList[bgIndex] + ')'; // 设置背景图片
};
```
希望这段代码能够帮到你!
相关问题
用html写一个可以通过按钮随机切换图片,图片拥有对应注释的页面
可以使用以下 HTML 和 JavaScript 代码来实现:<html>
<head>
<title>图片切换</title>
</head>
<body>
<h1>图片切换</h1>
<button onclick="changeImage()">切换图片</button>
<img id="image" src="image1.jpg" alt="图片1" />
<p id="caption">这是图片1的描述文字。</p> <script>
let images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let captions = ["这是图片1的描述文字。", "这是图片2的描述文字。", "这是图片3的描述文字。"]; function changeImage() {
let randomNumber = Math.floor(Math.random() * images.length);
document.getElementById("image").src = images[randomNumber];
document.getElementById("caption").innerHTML = captions[randomNumber];
}
</script>
</body>
</html>
在js中点击切换按钮能够随机显示图片
在JavaScript中,你可以通过创建一个函数来实现点击切换按钮随机显示图片的功能。以下是一个简单的示例:
```javascript
// 假设我们有三个图片元素和两个按钮
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var buttons = document.querySelectorAll('.switch-button');
// 首先,获取每个按钮并添加点击事件监听器
buttons.forEach(function(button) {
button.addEventListener('click', function() {
// 生成一个随机数
var randomIndex = Math.floor(Math.random() * images.length);
// 更改当前显示的图片src属性为随机选择的图片
document.getElementById('current-image').src = images[randomIndex];
});
});
// 假设有一个id为'current-image'的HTML元素用于显示图片
```
在这个例子中,我们假设你的HTML中有`<button class="switch-button">切换</button>`和`<img id="current-image" alt="图片">`这样的结构。每次点击切换按钮,都会随机选择一张图片显示。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)