Dark mode changer (深色模式切换器)

huangapple go评论67阅读模式
英文:

Dark mode changer

问题

我有以下代码:

<!doctype html>
<html>
<head>
</head>
<body>
  <div id="color-wrapper">
    Hello world
  </div>

  <input id="dark-mode" type="checkbox">
  <label for="dark-mode">Dark mode</label>
</body>
<style>
:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}
</style>
</html>

它应该在我勾选复选框后更改“Hello world”文本的背景颜色,但实际上没有,颜色始终是粉色。问题在哪里?

英文:

I have the following code:

&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div id=&quot;color-wrapper&quot;&gt;
    Hello world
  &lt;/div&gt;

  &lt;input id=&quot;dark-mode&quot; type=&quot;checkbox&quot;&gt;
  &lt;label for=&quot;dark-mode&quot;&gt;Dark mode&lt;/label&gt;
&lt;/body&gt;
&lt;style&gt;
:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}
&lt;/style&gt;
&lt;/html&gt;

It has to change background color of the "Hello world" text then I check the checkbox, but it does not, the color is always pink. What is the problem?

答案1

得分: 3

选择符 ~ 选择元素之后的同级元素,因此请更改您的 HTML 元素顺序以修复:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->
:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}

<!-- language: lang-html -->
<input id="dark-mode" type="checkbox">
<label for="dark-mode">Dark mode</label>
<div id="color-wrapper">
  Hello world
</div>

<!-- end snippet -->
英文:

The tilde selector ~ selects siblings after the element, so change order of elements in your html to fix:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}

<!-- language: lang-html -->

  &lt;input id=&quot;dark-mode&quot; type=&quot;checkbox&quot;&gt;
  &lt;label for=&quot;dark-mode&quot;&gt;Dark mode&lt;/label&gt;
    &lt;div id=&quot;color-wrapper&quot;&gt;
    Hello world
  &lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 06:26:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定