javascript - 如何使用 HTML 中的 <button> 在两个 CSS 文档之间切换

标签 javascript html css

我想在我的网页上使用深色主题和浅色主题,但我无法找到一种方法来只用一个按钮切换它们(所以第一次点击按钮打开深色主题,第二次点击它关了)。我希望能够在不使用第三方 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/

相关文章:

javascript - highcharts 的标注 CSS 实现不起作用

html - CSS3 "transform"属性在 IE9 中工作不同

javascript - Google map API 未显示在 MVC5 中

html - 在固定宽度的 div 内包装链接

javascript - 我如何解析来自 openlibrary api 的 Json 数据? (适本地)

html - 为什么我的网站上有这个正确的空白区域?

javascript - 下拉菜单在菜单按钮的边缘出现故障

javascript - Html 打印为 PDF - 如果表格在第二页上拆分,则不应用 Css

asp.net - 根据文化显示正确的日期格式

javascript - 使用请求在 node.js 中传输图像与发送回调正文