永久夜间模式切换

时间:2018-06-13 05:53:45

标签: javascript css button toggle



function swapstylesheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet)
}

<!--style.css-->

body{
	background-color:#ffffff;
}

li{
  color:#000000;
}
&#13;
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<li type="button" onclick="swapstylesheet('stylenight.css')">Night Mode</li>

<li type="button" onclick="swapstylesheet('style.css')">Day Mode</li>
</body>
&#13;
&#13;
&#13;

我正在尝试在我的HTML网站上实现一个按钮,该按钮使用JavaScript切换当前网站和我网站上所有其他网页的CSS。问题是,当我更改到其他CSS文件然后切换页面时,它会返回到原始CSS文件(请记住,我是JavaScript新手)。如果有任何帮助,这将是切换日/夜模式。

&#13;
&#13;
<!--stylenight.css-->

body{
	background-color:#000000;
}

li{
  color:#ffffff;
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

当用户点击日/夜模式按钮时,您必须在浏览器中设置Cookie。 并在用户返回原始页面时读取cookie值以设置模式。

您可以在此处阅读有关在javascript中设置和阅读Cookie的更多信息: https://www.w3schools.com/Js/js_cookies.asp

点击按钮,你看起来就是这样:

document.cookie = "mode=Day;";

此外,您还需要一个功能来在页面加载时读取cookie:

(来自How do I call a JavaScript function on page load?

window.onload = function() {
   readCookieAndSetMode();
};

readCookieAndSetMode()上,您应该使用

阅读Cookie

var x = document.cookie;

并依赖于x交换CSS(我将该部分留给您)。

答案 1 :(得分:0)

以上所有答案均不正确,我将在此处编写一些代码以供博客作者在自己的博客上应用暗模式。并一直保持到按下按钮为止...请在我的博客Hindi Tutor上进行检查。刷新页面时,100%正常工作,并且黑暗模式不会关闭。

<!-- Theme Functions JS -->
<script type='text/javascript'>
//<![CDATA[
function retheme() {
  var cc = document.body.className;
  if (cc.indexOf("darktheme") > -1) {
    document.body.className = cc.replace("darktheme", "");
    if (opener) {opener.document.body.className = cc.replace("darktheme", "");}
    localStorage.setItem("preferredmode", "light");
  } else {
    document.body.className += " darktheme";
    if (opener) {opener.document.body.className += " darktheme";}
    localStorage.setItem("preferredmode", "dark");
  }
}
(
function setThemeMode() {
  var x = localStorage.getItem("preferredmode");
  if (x == "dark") {
    document.body.className += " darktheme";
  }
})();
//]]>
</script>
<!-- theme switch is a button icon adjust this as your icon stylesheet -->
#theme-switch{font-size:20px;position:absolute;top:0;right:35px;z-index:19}
<!-- Here is your stylesheet for dark mode editd these colors and style name except body darktheme -->
body.darktheme{color:#fff;background-color:#000}
body.darktheme .your-element-name{color:#fff;background-color:#000}
body.darktheme .lin-element-name a{color:#fff;background-color:#000}
body.darktheme #your-element-name{color:#fff;background-color:#000}
body.darktheme your-element-name ul li a{color:#fff;background-color:#000}
<div id='theme-switch'>
<a class='fa fa-adjust' href='javascript:void(0);' onclick='retheme()' title='Change Theme'/>
    </div>