[英](Dark Mode) How do I get the background to change after the “dark-theme” is added?
所以我的網站上有一個按鈕,可以切換黑暗模式。 我在檢查中看到切換正在工作,但由於某種原因,#content .dark-theme沒有被看到。 我以為孩子優先。
HTML
<!-- Main Content -->
<div id="content">
CSS
#content {
background: rgb(248, 201, 201);
color: black;
}
#content .dark-theme {
background: rgb(49, 51, 71);
color: white;
}
JS
document.getElementById('change-theme-btn').addEventListener('click', function () {
content.classList.toggle('dark-theme');
});
在你的css中刪除.dark-theme之前的#content。
更改:
#content .dark-theme {
background: rgb(49, 51, 71);
color: white;
}
至
#content.dark-theme {
background: rgb(49, 51, 71);
color: white;
}
原因:擁有空格,意味着:具有“暗主題”類的項目,該項目是具有Id“內容”的項目的兒童。 沒有空間,它將變為“具有ID內容且類別為深色主題的項目”。
您應該使用#content.dark-theme
來正確定位您需要的元素; 在這里你可以看到這個在行動。
在CSS中,當您編寫: #content .dark-theme
您試圖使用類dark-theme
來定位元素,該類是具有id content
的元素的子元素。
在你的情況下,你想要的目標是元素#content
本身; 所以你應該寫: #content.dark-theme
或者#content
; 有了這個,你的目標是那個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.