几行代码快速让你的 博客、WordPress 或 其它站点 拥有 黑暗、夜间 模式
新的 Emin.ink 在菜单中增加了 开灯/关灯
选项,如果你的博客或站点也需要黑暗模式,白昼模式,这里提供 Emin.ink 实现黑暗模式的源码,可以参考一下。
准备
你需要准备 黑/白 两套样式用于切换
使用Cookie记录已开启或关闭的模式
切换按钮
<a href="#dark" id="bulb">关灯</a>
样式引入
将引入放置于style
标签内的最后一行,以实现样式覆盖。
<link rel="stylesheet" href="./css/<?php dark_mode()?>" type="text/css" id="dark_css">
PHP 检测
function dark_mode()
{
$EminBulb = $_COOKIE["EminBulb"];
if(isset($EminBulb))
{
if($EminBulb=="on")
{
echo 'dark_on.css';
}
else
{
echo 'light.css';
}
}
else
{
echo 'light.css';
}
}
切换脚本
<script>
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
var BulbStatus = getCookie("EminBulb")
if(BulbStatus!="")
{
document.getElementById('dark_css').href = './css/dark_on.css';
document.getElementById('bulb').text="开灯"
document.getElementById('bulb').title="进入白昼模式"
}
else
{
document.getElementById('bulb').text="关灯"
document.getElementById('bulb').title="进入夜晚模式"
}
document.getElementById('bulb').addEventListener('click', function(){
var BulbTips = document.getElementById('bulb').innerHTML
if(BulbTips=="关灯"){
document.getElementById('dark_css').href = './css/dark.css';
document.getElementById('bulb').text="开灯"
document.getElementById('bulb').title="进入白昼模式"
setCookie("EminBulb","on",7);
}
else{
document.getElementById('dark_css').href = './css/light.css';
document.getElementById('bulb').text="关灯"
document.getElementById('bulb').title="进入夜晚模式"
document.cookie = "EminBulb=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
})
</script>
CSS 样式
Dark.css:
html{
background-color:#1c1e1f;
transition: 1.5s;
min-height:100%
}
h1,h2,h3,h4,h5,h6,h7,ul,li,p,tr,table{
color:#c5c1b9;
}
a{
color:#c5c1b9;
}
textarea,input{
background-color: #333;
border: none;
color:white;
}
blockquote {
border-left: 4px solid #333;
}
code {
background-color: #555;
color: white;
}
Dark_on.css
html{
background-color:#1c1e1f;
min-height:100%
}
h1,h2,h3,h4,h5,h6,h7,ul,li,p,tr,table{
color:#c5c1b9;
}
a{
color:#c5c1b9;
}
textarea,input{
background-color: #333;
border: none;
color:white;
}
blockquote {
border-left: 4px solid #333;
}
code {
background-color: #555;
color: white;
}
Light.css
html{
background-color:#fff;
transition: 1.5s;
min-height:100%
}
h1,h2,h3,h4,h5,h6,h7,ul,li,p,tr,table{
color:#444;
}
a{
color:#111;
}
textarea,input{
background-color: white;
}
.children li {
border-left: 3px solid #000;
}
blockquote {
border-left: 4px solid #DDD;
}
code {
background-color: #F0F0F0;
color: #444;
}
HI 你好 十分喜欢您的博客 你的黑暗模式是怎么引入按键的 我的始终不兼容 可以分享一下您的源码么
感谢支持,源码我已经在文章中提及了