此问题已经在这里有了答案:
我希望JavaScript中的脚本能够通过单击按钮来更改活动样式表。我的代码如下:
index.html文件:
<head>
<script type="application/javascript" src="javascript.js">
<link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button id="stylesheet1" onclick="initate();"> Default Style Sheet </button>
<button id="stylesheet2" onclick='onclick="initate();"'> Dark Style Sheet </button>
</body>
javascript.js文件:
function swapStyleSheet(sheet) {
document.getElementById("pagestyle").setAttribute("href", sheet);
}
function initate() {
var style1 = document.getElementById("stylesheet1");
var style2 = document.getElementById("stylesheet2");
style1.onclick = swapStyleSheet("default.css");
style2.onclick = swapStyleSheet("dark.css");
}
default.css:
body{
background-color: white;
color: black
}
以及最后,dark.css:
body{
background-color: black;
color: white
}
但是它不起作用。你能帮助我吗?谢谢。
检查您的index.html
文件。在2号按钮的onclick中,您键入了onclick='onclick="initate();"'
,请键入onclick="initiate()"