在我的索引页面上,当我单击一个按钮时,页面背景会变为黑色,但在其他页面上不会,即使我将.js文件链接到所有html文档。我如何使背景变成黑色的所有页面上的按钮点击。
以下是到目前为止我得到的
function myFunction() {
document.getElementsByTagName("body")[0].style.cssText = "background: black;"
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<style>
body {
background: white;
}
</style>
</head>
<body>
<button id="button" onclick="myFunction()">Change to black</button>
</body>
</html>
您可以将背景颜色保存在localStorage中,并在页面加载时读取。每当你导航到网站的另一个页面(加载该脚本(时,它都会读取存储的值并相应地更改背景色。
脚本(customize.js(:
function setBGColor() {
var bgColor = localStorage.getItem("bgColor");
document.body.style.backgroundColor = bgColor;
}
function changeBGColor(newColor) {
localStorage.setItem("bgColor", newColor);
setBGColor();
}
setBGColor();
在您的HTML:中
...
<body>
<button id="button" onclick="changeBGColor('black')">Change to black</button>
</body>