网页加载时页面加载功能(js)不起作用

时间:2020-07-05 16:00:53

标签: javascript html

我一直试图找出如何调用在页面加载时启动的函数内部的函数以设置暗模式。

如果有人可以帮助我,我将非常感激。

这是我的js文件:

(function() {
  var darkSwitch = document.getElementById("darkSwitch");
  if (darkSwitch) {
    initTheme();
    darkSwitch.addEventListener("change", function(event) {
      resetTheme();
    });
    function initTheme() {
      var darkThemeSelected =
        localStorage.getItem("darkSwitch") !== null &&
        localStorage.getItem("darkSwitch") === "dark";
      darkSwitch.checked = darkThemeSelected;
      darkThemeSelected
        ? document.body.setAttribute("data-theme", "dark")
        : document.body.removeAttribute("data-theme");
    }
    function resetTheme() {
      if (darkSwitch.checked) {
        document.body.setAttribute("data-theme", "dark");
        localStorage.setItem("darkSwitch", "dark");
      } else {
        document.body.removeAttribute("data-theme");
        localStorage.removeItem("darkSwitch");
      }
    }
  }
})();

js文件来自此GitHub: https://github.com/coliff/dark-mode-switch

1 个答案:

答案 0 :(得分:0)

我认为您尝试在页面加载时处于暗模式。 这是您解决问题的方法。

此处是其文档:

这里是a link!这段代码来自Codepen

HTML:

<script>
    // Include this script near the top of your html
    var app = document.getElementsByTagName("BODY")[0];
    if (localStorage.lightMode == "dark") {
        app.setAttribute("data-light-mode", "dark");
    }
</script>

<h1>
    Dark Mode Toggle
</h1>
<p>Uses localStorage to store and apply the set light mode when page is loaded</p>
<button onclick="toggle_light_mode()">
    Toggle Light Mode
</button>

CSS


body {
    transition: background-color 0.3s;
    text-align: center;
    font-family: sans-serif;
    padding-top: 3em;
}

h1 {
    font-weight: normal;
}

button {
    padding: 1em;
    font-size: 1em;
    background: #000;
    color: #fff;
    border: none;
    cursor: pointer;
    transition: .3s;
}

button:hover {
    opacity:.5;
}

body[data-light-mode="dark"] {
    background-color: #000;
    color: #eee;
}
body[data-light-mode="dark"] button {
    background-color: #fff;
    color: #000;
}

JS


    function toggle_light_mode() {

        var app = document.getElementsByTagName("BODY")[0];

        if (localStorage.lightMode == "dark") {
            localStorage.lightMode = "light";
            app.setAttribute("data-light-mode", "light");
        } else {
            localStorage.lightMode = "dark";
            app.setAttribute("data-light-mode", "dark");
        }
        console.log("lightMode = " + localStorage.lightMode);
    }
相关问题