html css配色方案,如何过度使用css首选配色方案设置

我已经确定了一个合适的解决方案,如下所示:

CSS将使用变量和主题:

// root/default variables

:root {

--font-color: #000;

--link-color:#1C75B9;

--link-white-color:#fff;

--bg-color: rgb(243,243,243);

}

//dark theme

[data-theme="dark"] {

--font-color: #c1bfbd;

--link-color:#0a86da;

--link-white-color:#c1bfbd;

--bg-color: #333;

}

然后在必要时调用变量,例如:

//the redundancy is for backwards compatibility with browsers that do not support CSS variables.

body

{

color:#000;

color:var(--font-color);

background:rgb(243,243,243);

background:var(--bg-color);

}

JavaScript用于标识用户设置了哪个主题,或者如果用户已经覆盖了OS主题,以及在两者之间切换,这将包含在html输出之前的头中

:

//determines if the user has a set theme

function detectColorScheme(){

var theme="light"; //default to light

//local storage is used to override OS theme settings

if(localStorage.getItem("theme")){

if(localStorage.getItem("theme") == "dark"){

var theme = "dark";

}

} else if(!window.matchMedia) {

//matchMedia method not supported

return false;

} else if(window.matchMedia("(prefers-color-scheme: dark)").matches) {

//OS theme setting detected as dark

var theme = "dark";

}

//dark theme preferred, set document with a `data-theme` attribute

if (theme=="dark") {

document.documentElement.setAttribute("data-theme", "dark");

}

}

detectColorScheme();

这个javascript用于在设置之间切换,它不需要包含在页面的标题中,但是可以包含在任何位置

//identify the toggle switch HTML element

const toggleSwitch = document.querySelector('#theme-switch input[type="checkbox"]');

//function that changes the theme, and sets a localStorage variable to track the theme between page loads

function switchTheme(e) {

if (e.target.checked) {

localStorage.setItem('theme', 'dark');

document.documentElement.setAttribute('data-theme', 'dark');

toggleSwitch.checked = true;

} else {

localStorage.setItem('theme', 'light');

document.documentElement.setAttribute('data-theme', 'light');

toggleSwitch.checked = false;

}

}

//listener for changing themes

toggleSwitch.addEventListener('change', switchTheme, false);

//pre-check the dark-theme checkbox if dark-theme is set

if (document.documentElement.getAttribute("data-theme") == "dark"){

toggleSwitch.checked = true;

}

通过使用CSS变量和JavaScript,我们可以自动确定用户主题,应用它,并允许用户过度使用它。[截至本文撰写之时(2019/06/10),只有Firefox和Safari支持自动主题检测]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值