簡體   English   中英

用js改變字體顏色

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM