我有一个包含多个页面(多个 html 文件)的网站,我想在第一页上有一个按钮,单击该按钮时也会更改其他页面的背景颜色。
例如这两个文件(在同一文件夹中):
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type='text/css'>
button {
right: 50px;
width: 80px;
height: 80px;
border-radius: 30%;
font-size: 16px;
}
</style>
</head>
<body id=day-night>
<div>
<button id=change-background>Night Mode</button>
</div>
<a href='second_page.html'>Go to Second Page</a>
</body>
<script type='text/javascript'>
var backgroundMode = 0;
document.getElementsByTagName('button')[0].onclick=function() {
if (backgroundMode == 0) {
document.getElementById('day-night').style.backgroundColor='#000000';
backgroundMode = 1;
document.getElementById('change-background').innerHTML='Day Mode';
} else {
document.getElementById('day-night').style.backgroundColor='#ffffff';
backgroundMode = 0;
document.getElementById('change-background').innerHTML='Night Mode';
}
}
</script>
</html>
second_page.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body id=day-night>
<p>Some Text</p>
</body>
</html>
因此,如果我单击该按钮,它会将索引文件的背景颜色更改为黑色,但单击第二页的 anchor 元素,即使我对正文标记使用相同的 id <body id=day-night>
,背景也是白色的.
另外,作为一个附带问题: 从一页返回到另一页时,背景是否有可能保持相同的颜色?
最佳答案
JavaScript 变量和 DOM 更改不会跨页面或跨页面刷新持续存在。 您可以使用服务器端编码来为用户创建和维护 session 。 或者,您可以将背景颜色信息存储在 cookie 或本地存储中。当每个页面加载时,检查 cookie 或本地存储项的值并相应地应用背景颜色。
参见:
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
- https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
例如,如果您在第一页的 window.localStorage
对象上创建并设置 backgroundColor
键,则可以在第二页上执行此操作以应用DOM 加载时的背景颜色:
document.addEventListener("DOMContentLoaded", function(event) {
document.getELementById('day-night').style.backgroundColor=window.localStorage['backgroundColor'];
});
关于javascript - 如何使用 Javascript 更改多个 HTML 文档的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850191/