如何点击按钮切换100张背景图并通过Cookie保存?HTML/CSS/JS
先修复你原代码的核心问题
你原代码里用document.title操作的是网页的<title>标签,不是目标的.title类div。要选中正确元素,得用document.querySelector('.title')。修改后的基础单图切换代码如下:
HTML(无需修改)
<nav> <ul class="nav__list"> <li class="nav__list-item"> <a onclick="changeBackground()" class="nav__link nav__link--btn"> Change Theme </a> </li> </ul> </nav> <div class="title"></div>
修复后的JS(单图切换)
function changeBackground() { // 选中class为title的div const titleDiv = document.querySelector('.title'); // 设置背景图,建议加上尺寸适配 titleDiv.style.background = 'url(../img/bc/IMG_10.jpg) no-repeat'; titleDiv.style.backgroundSize = 'cover'; }
扩展:实现100张图随机切换+Cookie记忆状态
以下是完整实现逻辑:点击按钮随机切换100张图,用Cookie保存当前状态,页面刷新后自动恢复上次的背景图。
完整JS代码
// 从Cookie读取保存的图片索引 function getSavedImageIndex() { const cookies = document.cookie.split('; '); for (const cookie of cookies) { const [name, value] = cookie.split('='); if (name === 'currentBgImage') { return parseInt(value); } } // 无保存记录时默认用第1张 return 1; } // 将图片索引存入Cookie,有效期30天 function saveImageIndex(index) { const expiry = new Date(); expiry.setDate(expiry.getDate() + 30); document.cookie = `currentBgImage=${index}; expires=${expiry.toUTCString()}; path=/`; } // 根据索引设置背景图 function setBackgroundImage(index) { const titleDiv = document.querySelector('.title'); titleDiv.style.background = `url(../img/bc/IMG_${index}.jpg) no-repeat center center`; titleDiv.style.backgroundSize = 'cover'; } // 切换背景图主函数 function changeBackground() { const currentIndex = getSavedImageIndex(); // 生成和当前不同的随机索引(1-100) let newIndex; do { newIndex = Math.floor(Math.random() * 100) + 1; } while (newIndex === currentIndex); // 更新背景并保存状态 setBackgroundImage(newIndex); saveImageIndex(newIndex); } // 页面加载时自动恢复上次的背景图 window.addEventListener('load', () => { const savedIndex = getSavedImageIndex(); setBackgroundImage(savedIndex); });
额外提示
- 确保图片路径正确:
../img/bc/是相对当前HTML文件的路径,路径错误会导致背景图加载失败 - 建议给
.titlediv设置固定宽高,否则可能看不到背景图:
.title { width: 100%; height: 500px; }
内容的提问来源于stack exchange,提问作者Begonio
相关产品推荐
相关产品推荐

