js点击更换背景图并保存到cookie
时间: 2023-12-21 19:06:42 浏览: 23
你可以使用以下代码实现点击更换背景图并保存到 cookie:
HTML 代码:
```html
<button id="change-bg">更换背景</button>
```
JavaScript 代码:
```javascript
// 获取按钮和 body 元素
const changeBgBtn = document.getElementById("change-bg");
const body = document.getElementsByTagName("body")[0];
// 获取当前背景图的序号
let currentBgIndex = parseInt(getCookie("bgIndex")) || 0;
// 背景图列表
const bgList = [
"https://example.com/bg1.jpg",
"https://example.com/bg2.jpg",
"https://example.com/bg3.jpg",
];
// 切换背景图
changeBgBtn.addEventListener("click", () => {
currentBgIndex = (currentBgIndex + 1) % bgList.length;
body.style.backgroundImage = `url(${bgList[currentBgIndex]})`;
setCookie("bgIndex", currentBgIndex);
});
// 设置 cookie
function setCookie(key, value) {
document.cookie = `${key}=${value};path=/`;
}
// 获取 cookie
function getCookie(key) {
const cookieArr = document.cookie.split(";");
for (let i = 0; i < cookieArr.length; i++) {
const [cookieKey, cookieValue] = cookieArr[i].split("=");
if (cookieKey.trim() === key) {
return cookieValue.trim();
}
}
return null;
}
```
上面的代码中,我们定义了一个 `bgList` 数组,保存了所有的背景图片地址。然后,我们在点击按钮时,切换当前背景图,并将当前背景图的序号保存到 cookie 中。在页面加载时,我们获取当前背景图的序号(如果没有保存过,则默认为 0),并设置为背景图。