点击更换背景按钮,实现网页的背景图的改变body
时间: 2024-05-03 17:17:10 浏览: 13
可以通过JavaScript来实现更换背景图的功能。可以先在HTML中添加一个按钮,然后在JavaScript中给按钮添加点击事件,当按钮被点击时,改变body的背景图。
HTML代码如下:
```html
<button id="change-background-btn">更换背景</button>
```
JavaScript代码如下:
```javascript
const changeBackgroundBtn = document.querySelector('#change-background-btn');
const body = document.querySelector('body');
const backgrounds = ['url(background1.jpg)', 'url(background2.jpg)', 'url(background3.jpg)'];
changeBackgroundBtn.addEventListener('click', () => {
const randomBackgroundIndex = Math.floor(Math.random() * backgrounds.length);
const randomBackground = backgrounds[randomBackgroundIndex];
body.style.backgroundImage = randomBackground;
});
```
以上代码会先获取到按钮和body元素,然后给按钮添加一个点击事件。当按钮被点击时,会从backgrounds数组中随机选择一个背景图,然后把它设置为body的背景图。
相关推荐
![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)