[英]How can I use Toggle Function with NodeList/Array to toggle dark mode in all sections with same class?
这是 HTML 代码:
<div class="page" id="page-home">
<!-- Blueprint header -->
<header class="header cf">
<img class="poster" src="images/Logo_square.png" style="" alt="Logo" />
<h1 class="header__title">Experts in .......</h1>
<br>
<p class="header__desc">Let's get ➲ <a id="quote">Connected</a></p>
<button onclick="myFunction()">Toggle dark mode</button>
</header>
</div>
<div class="page" id="page-services">....</div>
<div class="page page--inactive" id="page-aboutus">.....</div>
<div class="page page--inactive" id="page-contactus">...</div>
<div class="page page--inactive" id="page-projects">....</div>
<div class="page page--inactive" id="page-history">.....</div>
我想让切换按钮将所有具有class=" page"
和class="page page--inactive"
的类更改为我设置的class=" page page_dark"
和class=" page page_dark page--inactive"
暗模式 colors。 我已经尝试了下面提到的代码,但它不起作用
function myFunction() {
document.body.classList.toggle("body_dark");
var page_list = document.querySelectorAll('.page');
var page_array = [page_list]; // converts NodeList to Array
for(var i = 0 ; i < page_array.length; i++){
console.log(page_array[i]);
page_array[i].classList.toggle("page_dark");
}
}
样式表如下:
.body_dark{
color: #bdbdbd;
background: #1d1e21 !important;
}
body {
font-family: 'Avenir Next', Avenir, 'Helvetica Neue', 'Lato', 'Segoe UI', Helvetica, Arial, sans-serif;
margin: 0;
color: #696969;
background: #e7e7e7;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
overflow-y:auto;
}
.js .page.page_dark {
background: linear-gradient(#333 -2%, #000000 1%);
}
.js .page {
position: relative;
z-index: 5;
overflow: auto;
width: 100%;
height: 100vh;
pointer-events: auto;
background: linear-gradient(#eee -2%, #ffffff 1%);
box-shadow: 0 -1px 10px rgba(0, 0, 0, 0.1);
}
如果您可能需要查看有关代码的更多详细信息,请在下面发表评论,我很乐意分享。 我没有使用id
,因为有字体 colors 并且随着其他页面上的内容而变化,使用不同的id
单独更新会让人头疼。
先生,我改变了一点。
转换为数组应使用...展开运算符。
function myFunction() {
document.body.classList.toggle("body_dark");
var page_list = document.querySelectorAll(".page");
var page_array = [...page_list]; // converts NodeList to Array
page_array.forEach((page) => {
page.classList.toggle("page_dark");
});
}
如果您使用的是 IE,请在 Chrome 或 FF 上查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.