【问题标题】:How to toggle between two CSS documents with a <button> in HTML如何在 HTML 中使用 <button> 在两个 CSS 文档之间切换
【发布时间】:2019-09-02 02:35:54
【问题描述】:

我正在尝试在我的网页上使用深色主题和浅色主题,但我找不到仅通过一个按钮来切换它们的方法(因此第一次单击按钮会打开深色主题,第二次会打开它关了)。我希望能够在不使用第三方 JavaScript 库的情况下做到这一点。我找到了一种使用&lt;option&gt; 元素的方法,但这不是我想要的“切换按钮”:

  <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');
    }
}

感谢您的帮助!

【问题讨论】:

标签: javascript html css


【解决方案1】:

另一种方法是使用布尔值。您可以在每次单击时更改布尔值。您可以使用此布尔值切换 css。

<button onclick=getTheme()>Click to use this theme.</button>

JS

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);
}

根据评论编辑

这确实很好用,但是,有没有办法使用 document.getElementById("themeToggle").innerHTML = "New text!";用这个来改变“深色主题”或“浅色主题”之间的按钮

你可以使用同样的逻辑,比如:

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);
}

【讨论】:

  • 这确实很好用,但是,有没有办法使用document.getElementById("themeToggle").innerHTML = "New text!"; 来更改“深色主题”或“浅色主题”之间的按钮
  • 很好的答案
【解决方案2】:

我知道这看起来有点业余,但你可以这样做,

<button onclick=getTheme() id=themeToggle>Click to use this theme.</button>
<script>
var click = 0;
function getTheme()
{   
    click++;
    if(click%2 == 0)
        changeTheme('css/dark.css');
    else
        changeTheme('css/main.css');
}
</script>

并相应地更改按钮上的文本。让我知道它是否有效。

【讨论】:

    【解决方案3】:

    一个简单的方法是:

    HTML

    <input type="button" value="Dark" id="button" onclick=getTheme()></input> 
    

    JavaScript

    function getTheme () {
      var button = document.getElementById("button");
        if(button.value === "Dark") {
          button.value = "Revert To Original";
        } else {
          button.value = "Dark";
        }
    }
    

    在 if/else 中,您可以放置​​更改主题功能。

    https://codepen.io/anon/pen/xedzVz?editors=1111

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 2023-02-21
      • 2023-03-07
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多