使用单选按钮在两个音节之间切换

问题描述 投票:2回答:1

我想有一个切换按钮,可以在明暗主题之间切换。我可以切换一次,但之后不会切换回去。我当前的方法是:

<link id="theme-css" class="dark-theme" rel="stylesheet" href="{% static 'css/dashboard-dark.css' %}">

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="customSwitches" onclick="toggle()">
  <label class="custom-control-label" for="customSwitches">Toggle Theme</label>
</div>

<script>
    function toggle() {
      if(document.getElementById("theme-css").href="{% static 'css/dashboard-dark.css' %}"){
        document.getElementById("theme-css").href="{% static 'css/dashboard-light.css' %}"; 
      }
      else if(document.getElementById("theme-css").href="{% static 'css/dashboard-light.css' %}"){
        document.getElementById("theme-css").href="{% static 'css/dashboard-dark.css' %}"; 
      }
    }
</script>
javascript html css
1个回答
0
投票

让我们看看。首先要注意的是,您正在寻找toggle类型的功能。进行切换时,您希望将状态保持在某处。无论是在html元素本身上还是在javascript对象中。

我将以主题的初始状态加载脚本。假设是轻主题,并将该值存储在javascript变量中。

因此,每次调用toggle函数时,您查询js变量状态,并根据该主题交换主题。

所以您将执行以下操作:

// Some variable called state holds the theme state
var link = document.getElementById("theme-css");
if(state == 'light')
     link.href = "<the-dark-uri-css-path>";
else
     link.href = "<the-light-uri-css-path>";
// The you toggle the state val
state = state=='light'? 'dark' : 'light';

请记住,您可以将其构建为对象并将主题的状态保留在对象属性内。

© www.soinside.com 2019 - 2024. All rights reserved.