使用JS浏览器选项卡/主题颜色切换

其概念是,单击按钮时,页面内容的配色方案将与浏览器选项卡颜色一起切换为暗模式。我想出了这个:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<style>

body {
  padding: 25px;
  background-color: #ddd;
  color: black;
  font-size: 25px;
}

.btn {
    background: white;
    border: 1px solid #10101c;
    color: grey;
}

.dark-mode {
  background-color: #10101c;
  color: #778899;
}

.dark-mode .btn {
    background: #10101c;
    color: red;
    border: 1px solid #002e43;
}

</style>
</head>
<body>

<h2>Toggle Dark/Light Mode</h2>
<p>Click the button to toggle between dark and light mode for this page.</p>
<button class="btn" onclick="toggle()">Toggle dark mode</button>

<script>
function toggle() {
    var element = document.body;
    element.classList.toggle("dark-mode");
    var yo = document.querySelector("meta[name=theme-color]");

    if yo.hasAttribute("content", "#ffffff");
    {
    yo.setAttribute("content", "#10101c"); 
    }
    else {
    yo.setAttribute("content", "#ffffff");
    }
}
</script>

</body>
</html>

我要去哪里错了?集中的主要领域是JS领域。 ps。我是JS新手

评论