[英]Change font color with js
我想改变
id="navbar"
当页面处于深色模式时字体颜色,当页面切换到浅色模式时使字体颜色恢复。 开关是用js做的:
const onClick = () => {
theme.value = theme.value === 'light'
? 'dark'
: 'light'
setPreference()
}
const getColorPreference = () => {
if (localStorage.getItem(storageKey))
return localStorage.getItem(storageKey)
else
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
const setPreference = () => {
localStorage.setItem(storageKey, theme.value)
reflectPreference()
}
const reflectPreference = () => {
document.firstElementChild
.setAttribute('data-theme', theme.value)
document
.querySelector('#theme-toggle')
?.setAttribute('aria-label', theme.value)
}
const theme = {
value: getColorPreference()
}
背景设置在这里
html {
background: linear-gradient(135deg, #a1c4fd 10%, #c2e9fb 90%);
block-size: 100%;
color-scheme: light;
background-attachment: fixed;
}
html[data-theme=dark] {
background: linear-gradient(135deg, #061c43 10%, #08101f 90%);
color-scheme: dark;
background-attachment: fixed;
}
#navbar ul li[data-theme=dark] {
padding: 10px;
border-radius: 25px;
float: right;
margin-left: 3px;
margin-right: 8px;
font-weight: 500;
color: white;
box-shadow: -5px -5px 8px #ffffff60,5px 5px 10px #00000060;
}
那没有做任何事情。 我错过了什么?
如果你想使用 js 更改元素的颜色,你必须在这个例子中了解 DOM HTML 我正在尝试更改某些元素的颜色
<!DOCTYPE html>
<html>
<body>
<h2 id="myH2">This is an example h2</h2>
<p id="myP">This is an example paragraph.</p>
<p id="myP2">This is also an example paragraph.</p>
<div id="myDiv">This is an example div.</div>
<br>
<button type="button" onclick="myFunction()">Set text color</button>
<script>
function myFunction() {
document.getElementById("myH2").style.color = "#ff0000";
document.getElementById("myP").style.color = "magenta";
document.getElementById("myP2").style.color = "blue";
document.getElementById("myDiv").style.color = "lightblue";
}
</script>
</body>
</html>
只需这样做:
const reflectPreference = () => {
document.firstElementChild.setAttribute('data-theme', theme.value);
document.querySelector('#theme-toggle')?.setAttribute('aria-label', theme.value);
document.getElementById("navbar").style.fontColor = theme.value === "dark" ? "white" : "black";
}
在这里阅读更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.