4 回答
TA贡献1798条经验 获得超7个赞
实际上你的代码中有一些错别字和错误,这不仅仅是关于 innerHTML。检查片段。
document.getElementById("myButton").addEventListener("click", function (e) {
document.body.classList.toggle('dark-mode');
// element.classList.toggle("dark-mode");
if (e.target.textContent === "Dark Mode") {
e.target.textContent = "Day Mode";
} else {
e.target.textContent = "Dark Mode";
}
});
<body>
<h1>COLOR SHIFTER: Day/Night Mode</h1>
<p>Click the button to see some magic! Toggle between Day and Night mode! Give it a try!</p>
<br><br><br><br>
<button id="myButton">Dark Mode</button>
</body>
TA贡献1877条经验 获得超1个赞
使用 innerHTML 设置/获取按钮文本。另外,如果你想轻松调试你的JS,你可以使用浏览器调试工具(F12->控制台)。
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" />
<title>Button Shifter</title>
<style>
.dark-mode {
background-color: black;
}
.whiteText {
color: white;
}
</style>
</head>
<body>
<div id="heading">
<h1 class="paraText1">COLOR SHIFTER: Day/Night Mode</h1>
<p class="paraText">
Click the button to see some magic! Toggle between Day and Night mode!
Give it a try!
</p>
</div>
<br /><br /><br /><br />
<button onclick="toggleTheme()" id="myButton">Dark Mode</button>
</body>
<script>
function toggleTheme() {
document.body.classList.toggle("dark-mode");
document.getElementById("heading").classList.toggle("whiteText");
var btn = document.getElementById("myButton");
if (btn.innerHTML == "Night Mode") {
btn.innerHTML = "Day Mode";
} else {
btn.innerHTML = "Night Mode";
}
}
</script>
</html>
TA贡献1784条经验 获得超2个赞
const nightText = "Night Mode";
const dayText = "Day Mode";
function toggleTheme(button) {
document.querySelector("body").classList.toggle('dark-mode'); // have a look at querySelector :)
button.classList.toggle("dark-mode");
if (button.textContent == nightText){
button.textContent = dayText;
}else {
button.textContent = nightText;
}
}
.dark-mode {
background-color: #333333;
color: #dddddd;
}
<body>
<h1>
COLOR SHIFTER: Day/Night Mode
</h1>
<p>
Click the button to see some magic! Toggle between Day and Night mode! Give it a try!
</p>
<!-- Use css to modify the layout of your page, not <br/> :) -->
<button onclick="toggleTheme(this)">
Night Mode
</button>
<script src="Javascript.js"></script>
</body>
TA贡献1862条经验 获得超6个赞
function toggleTheme() {
document.body.classList.toggle('dark-mode');
var btn = document.getElementById("myButton");
if (btn.textContent === "Dark Mode") return btn.textContent = "Day Mode";
btn.textContent = "Dark Mode"
}
添加回答
举报