[英]Light and Dark mode based on system setting and button click in html
I have the following code on my website where I am trying to set light or dark mode based on the settings of the users system/browser as well as the ability to change the setting based on a button press.我的网站上有以下代码,我试图根据用户系统/浏览器的设置设置浅色或深色模式,以及根据按下按钮更改设置的能力。
What I want to happen is:我想要发生的是:
Perhaps I am missing something here to get it all functioning correctly?也许我在这里遗漏了一些让一切正常运行的东西? Mainly the buttons do not switch.主要是按键不切换。
function lightDark() { var el = document.querySelectorAll(".light, .dark") if (el.href.match("light.css")) { el.href = "dark.css"; } else { el.href = "light.css"; } } < script type = "text/javascript" > $('#lightDarkToggle').click(function() { if (window.matchMedia('prefers-color-scheme: dark').matches) { $(this).find('i').toggleClass('fa-sun'), el.href = "dark.css"; } else { $(this).find('i').toggleClass('fa-moon'), el.href = "light.css"; } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link class="light" rel="stylesheet" href="light.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)" /> <link class="dark" rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)" /> <button id="lightDarkToggle" onclick="lightDark()"><i class="fas fa-moon"></i></button>
I think this line var el = document.querySelectorAll("#light, #dark")
should be var el = document.querySelectorAll(".light, .dark")
, because your link tags have a class, not an id.我认为这一行var el = document.querySelectorAll("#light, #dark")
应该是var el = document.querySelectorAll(".light, .dark")
,因为你的链接标签有 class,而不是 id。
Another thing, in your second script tag, you try to update el.href
, but in this function, el
is never defined.另一件事,在你的第二个脚本标签中,你尝试更新el.href
,但在这个 function 中, el
从未被定义。 It has been defined in another function ( lightDark()
), so it is not accessible anymore at the end of it.它已在另一个 function ( lightDark()
) 中定义,因此在它的末尾无法再访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.