简体   繁体   English

基于系统设置和按钮点击的明暗模式 html

[英]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:我想要发生的是:

  1. It is daytime orthe users browser is set to light.现在是白天,或者用户的浏览器设置为亮灯。 The website loads the light.css and the button shows the moon icon to switch to the light theme.该网站加载了 light.css 并且按钮显示了月亮图标以切换到灯光主题。
  2. It is night time or the user has their theme set to dark mode.现在是晚上,或者用户将他们的主题设置为深色模式。 The website loads the dark.css theme and the icon in the button switches to the sun.该网站加载了 dark.css 主题,按钮中的图标切换为太阳。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM