切换暗模式 - 新创建元素的问题

Toggle dark mode - Problem with newly created elements

我想用 click 事件使 JS 暗模式切换 但它有效 使用 HTML 元素,但它不适用于使用 DOM.

使用 JavaScript 创建的元素

let body = document.querySelector(`body`);
let input = document.querySelector(`.input`);
let addBtn = document.querySelector(`.add`);
let form = document.querySelector(`.form`);
let container = document.querySelector(`.tasks`);

form.addEventListener(`submit`, (e) => {
  e.preventDefault();
  const task = input.value;
  if (!task) {
    window.alert(`please fill the input!`);
  } else {
    const taskEl = document.createElement(`div`);
    taskEl.classList.add(`task`);

    const taskContentEl = document.createElement(`div`);
    taskContentEl.appendChild(document.createTextNode(task));
    taskEl.appendChild(taskContentEl);
    container.appendChild(taskEl);

    input.value = ``;
  }
});

function darkMode() {
  let darkBtn = document.querySelector(`.btn`);

  darkBtn.onclick = () => {
    form.classList.toggle(`formDark`);
    input.classList.toggle(`inputDark`);
    body.classList.toggle(`bodyDark`);
    //here is the code that's not works 
    taskEl.classList.toggle(`inputDark`);
  };
}
darkMode();
<button type="button" class="btn">Dark mode</button>
<form class="form">
<input>
</form>
<div class="tasks"></div>

在第一个事件侦听器上,您可以检查 body 标签上是否已存在暗模式

form.addEventListener(`submit`, (e) => {

  e.preventDefault();

  const task = input.value;

  const createTaskEl = () => {
    const taskEl = document.createElement(`div`);
    taskEl.classList.add(`task`);

    const taskContentEl = document.createElement(`div`);
    taskContentEl.appendChild(document.createTextNode(task));
    taskEl.appendChild(taskContentEl);
    container.appendChild(taskEl);

    input.value = ``;
  }  

  if (!task) {
    window.alert(`please fill the input!`);

  } else {

      // Check if the body element is already in in dark mode
      if(!body.classList.contains('bodyDark')){
        createTaskEl()
      } else {
        createTaskEl()
        let taskEl = document.querySelector(`.task`);
        taskEl.classList.add(`inputDark`);
      }
  }
});

您需要先检查 taskEl 是否存在。

function darkMode() {

  let darkBtn = document.querySelector(`.btn`);

    darkBtn.onclick = () => {

        let taskEl = document.querySelector(`.task`);

        const primaryEls = () => {
            form.classList.toggle(`formDark`),        
            input.classList.toggle(`inputDark`),
            body.classList.toggle(`bodyDark`)
        }

        if(taskEl){
            primaryEls();
            taskEl.classList.toggle(`inputDark`); 
        } else {
            primaryEls();
        }
    };
}

查看此答案: 了解如何使用 LocalStorage 实现 暗模式 切换。


现在或未来的元素上切换暗模式样式?

简单。不要使用所有元素的特定 JS 列表来切换 classes from.
只需在 body 元素上切换 "dark" class。 然后,使用 CSS 设置其他所有样式:

document.body.classList.toggle("dark");
.dark .input {}
.dark .add {}
.dark .someFutureElement {}

重制代码的示例:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const els = (sel, par) => (par || document).querySelectorAll(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// App: Tasks

const elInput = el(`#taskInput`);
const elAdd = el(`#taskAdd`);
const elForm = el(`#taskForm`);
const elTasks = el(`#tasks`);

const createTask = (task) => {
  tasks.push(task);
  const elTask = elNew(`li`, {textContent: task, className: "task"});
  elTasks.append(elTask);
};

elForm.addEventListener(`submit`, (evt) => {
  evt.preventDefault();
  const task = elInput.value.trim(); // Trim from whitespaces!
  if (!task) return alert(`Please, fill the input!`);
  createTask(task);
  elInput.value = ``;
});

// Init: Populate existing tasks
const tasks = ["Drink coffee", "Develop some app"];
tasks.forEach(createTask);


// App: Dark mode

const elBody = el(`body`);
const elToggleDark = el(`#toggleDark`);
elToggleDark.addEventListener("click", () => {
  elBody.classList.toggle("dark", elToggleDark.checked);
});
.dark {
  background: #333;
  color: #fff;
}

.dark #taskInput {
  background: rgba(255,255,255,0.2);
  color: #fff;
}

.dark ol {
  border: 1px solid rgba(255,255,255,0.2);
}
<label><input type="checkbox" id="toggleDark"> Toggle Dark Mode</label>

<form id="taskForm">
  <input id="taskInput" type="text" placeholder="Task...">
  <button id="taskAdd">Add</button>
</form>

<ol id="tasks"></ol>