我想在我的网页上使用深色主题和浅色主题,但我无法找到一种方法来只用一个按钮切换它们(所以第一次点击按钮打开深色主题,第二次点击它关了)。我希望能够在不使用第三方 JavaScript 库的情况下执行此操作。我找到了一种使用 <option>
执行此操作的方法元素,但这不是我想要的“切换按钮”:
<button onclick=getTheme() id=themeToggle>Click to use this theme.</button>
<select id="select">
<option>Dark Theme</option>
<option>Revert To Original</option>
</select>
和
function getTheme () {
function changeTheme (Theme) {
document.getElementById('style').setAttribute('href', Theme);
}
var index = document.getElementById("select").selectedIndex;
switch (index) {
case 0:
changeTheme('css/dark.css');
break;
case 1: changeTheme('css/main.css');
}
}
感谢您的帮助!
最佳答案
另一种方法是使用 bool 值。您可以在每次单击时更改 bool 值。您可以使用此 bool 值切换 css。
<button onclick=getTheme()>Click to use this theme.</button>
J
var bool = true;
function getTheme() {
function changeTheme (theme) {
document.getElementById('style').setAttribute('href', theme);
}
bool = !bool;
var theme = bool ? 'css/dark.css' : 'css/main.css';
changeTheme(theme);
}
根据评论编辑
This does work perfectly, however, is there a way to use document.getElementById("themeToggle").innerHTML = "New text!"; with this to change the button between "dark theme" or "light theme"
您可以使用相同的逻辑,例如:
var bool = true;
function getTheme() {
function changeTheme (theme, text) {
document.getElementById('style').setAttribute('href', theme);
document.getElementById('themeToggle').innerText = text;
}
bool = !bool;
var theme = bool ? 'css/dark.css' : 'css/main.css';
var text = bool ? 'Dark theme' : 'Light theme';
changeTheme(theme, text);
}
关于javascript - 如何使用 HTML 中的 <button> 在两个 CSS 文档之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632813/