簡體   English   中英

如何使用 Toggle Function 和 NodeList/Array 在具有相同 class 的所有部分中切換暗模式?

[英]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 &#x27B2; <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.

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