简体   繁体   English

(暗模式)添加“暗主题”后,如何更改背景?

[英](Dark Mode) How do I get the background to change after the “dark-theme” is added?

so I have a button on my website that is supposed to toggle dark mode. 所以我的网站上有一个按钮,可以切换黑暗模式。 I see in my inspection that the toggle is working but for some reason, the #content .dark-theme isn't being seen. 我在检查中看到切换正在工作,但由于某种原因,#content .dark-theme没有被看到。 I thought that the child took precedence. 我以为孩子优先。

HTML HTML

<!-- Main Content -->
  <div id="content">

CSS CSS

    #content {
    background: rgb(248, 201, 201);
    color: black;
}

#content .dark-theme {
    background: rgb(49, 51, 71);
    color: white;
}

JS JS

document.getElementById('change-theme-btn').addEventListener('click', function () {
content.classList.toggle('dark-theme');

}); });

在你的css中删除.dark-theme之前的#content。

Change: 更改:

#content .dark-theme {
    background: rgb(49, 51, 71);
    color: white;
}

to

#content.dark-theme {
    background: rgb(49, 51, 71);
    color: white;
}

Reason: Having the space, means: An item with class 'dark-theme' which is a CHILDREN of an item with Id "content". 原因:拥有空格,意味着:具有“暗主题”类的项目,该项目是具有Id“内容”的项目的儿童。 Without the space, it becomes "An item which has Id content AND class dark-theme". 没有空间,它将变为“具有ID内容且类别为深色主题的项目”。

You should use #content.dark-theme to correctly target the element you need; 您应该使用#content.dark-theme来正确定位您需要的元素; here you can see this in action. 在这里你可以看到这个在行动。

In CSS, when you write: #content .dark-theme you are trying to target the element with a class dark-theme that is a child of an element with an id content . 在CSS中,当您编写: #content .dark-theme您试图使用类dark-theme来定位元素,该类是具有id content的元素的子元素。

In your case, what you want to target is the element #content itself; 在你的情况下,你想要的目标是元素#content本身; so you should write: #content.dark-theme or just #content ; 所以你应该写: #content.dark-theme或者#content ; with this you are targeting the element #content that ALSO has a class dark-theme 有了这个,你的目标是那个ALSO有一个类dark-theme的元素#content

 document.getElementById('change-theme-btn').onclick = function() { content.classList.toggle('dark-theme'); } 
 #content { background: rgb(248, 201, 201); color: black; height: 150px; } #content.dark-theme { background: rgb(49, 51, 71); color: white; } 
 <div id="content"> This is content </div> <button id="change-theme-btn">Change</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM