首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用js更改字体颜色

用js更改字体颜色
EN

Stack Overflow用户
提问于 2022-11-27 12:34:25
回答 2查看 55关注 0票数 0

我想换一下

代码语言:javascript
复制
id="navbar"

当页面处于暗模式时字体颜色,并在页面切换到光模式时使字体颜色返回。开关是用js完成的:

代码语言:javascript
复制
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()
}

背景设置在这里

代码语言:javascript
复制
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;
    
}
代码语言:javascript
复制
#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;
}

那什么都没做。我遗漏了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-27 15:13:30

只需这样做:

代码语言:javascript
复制
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";
}

阅读更多的这里

票数 0
EN

Stack Overflow用户

发布于 2022-11-27 13:56:31

如果您想使用js更改元素的颜色,那么您必须在这个示例中了解DOM -我正在尝试更改一些元素的颜色

代码语言:javascript
复制
<!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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74590058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档