Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <main>
  <div class="container m-auto max-w-lg mt-10">
    <div class="border bg-yellow-100 rounded-lg px-5 py-5 shadow-lg shadow-yellow-600/50">
      <div class="flex">
        <input id="todoField" class="flex-1 p-2 mr-4 border-2 border-sky-600 rounded-lg outline-none" type="text" placeholder="新增待辦事項" />
        <select id="category" class="p-2 mr-4 border-2 border-sky-600 rounded-lg outline-none" onchange="addTodotheme()">
          <option value="normal">一般</option>
          <option value="important">重要</option>
          <option value="urgent">緊急</option>
        </select>
        <button id="addTodoBtn" class="text-slate-300 font-semibold tracking-widest px-8 py-2 bg-sky-600 rounded-md hover:bg-opacity-70 outline-none" onclick="addTodo()">
          新增
        </button>
      </div>
      <div id="todoBox" class="mt-4 border-t-2 hidden">
        <div class="flex items-center my-4">
          <h2 class="text-slate-500 font-semibold mr-auto">Tasks</h2>
          <button class="bg-slate-500 text-white px-3 py-1 rounded-md hover:bg-opacity-70 mr-2" onclick="exportText()">
            匯出
          </button>
          <button class="bg-green-500 text-white px-3 py-1 rounded-md hover:bg-opacity-70" onclick="save()">
            儲存
          </button>
        </div>
        <ul id="todolist" class="mt-1">
        </ul>
      </div>
    </div>
  </div>
</main>
              
            
!

CSS

              
                body {
  font-family: "Noto Sans TC", sans-serif;
}

              
            
!

JS

              
                // 新增一筆
function addTodo() {
  // 變數以$開頭表示是選取html的元素
  const $todoField = document.querySelector("#todoField"); // input
  const $todolist = document.querySelector("#todolist"); // ul
  const $category = document.querySelector("#category"); // select

  // 創建li, span, button元素
  const newLi = document.createElement("li");
  const newSpanIcon = document.createElement("span");
  const newSpanDone = document.createElement("span");
  const newSpanText = document.createElement("span");
  const newBtn = document.createElement("button");

  // 沒有輸入內容就跳提醒,使用return程式就不會再往下執行
  if (!$todoField.value) return alert("請輸入待辦事項內容");

  // 取得一般、重要、緊急的選擇結果
  const selectedValue = $category[$category.selectedIndex].value;

  // 依照一般、重要、緊急的選擇結果,判斷要輸出的class樣式
  const selectedStyle =
    selectedValue == "normal"
      ? "sky"
      : selectedValue == "important"
      ? "orange"
      : "red";

  // 使用dataset屬性,在待辦事項中加入normal, important, urgent識別,方便在匯出純文字時使用
  newLi.dataset.priority = selectedValue;

  // 幫創建的li元素加上class樣式
  newLi.classList.add(
    `bg-${selectedStyle}-300`,
    "flex",
    "items-center",
    "text-slate-700",
    "p-3",
    "mb-2",
    "rounded-sm",
    "shadow-lg"
  );

  // 幫創建的button元素加上class樣式
  newBtn.classList.add(
    "text-slate-300",
    "font-semibold",
    "tracking-widest",
    "px-3",
    "py-1",
    "bg-rose-600",
    "rounded-md",
    "hover:bg-opacity-70",
    "ml-auto"
  );

  // 幫創建的button元素加入文字內容
  newBtn.textContent = "刪除";

  // 幫創建的button元素加上刪除功能(delTodo is a Function)
  // newBtn.onclick = delTodo;

  // 使用removeChild()
  newBtn.addEventListener("click", () => {
    $todolist.removeChild(newLi);
    save();
    showHiddenTodo();
  });

  // 幫創建的span元素加入樣式和user輸入的待辦事項內容
  newSpanIcon.innerHTML = "&#10004;";
  newSpanIcon.className =
    "w-6 h-6 bg-gray-300 text-white rounded-full text-center hover:opacity-70 mr-3 cursor-pointer";
  newSpanIcon.onclick = todoDone;

  newSpanDone.textContent = "已完成";
  newSpanDone.className = "bg-slate-400 text-white rounded-lg p-1 text-xs mr-1";
  newSpanDone.style.display = "none";

  newSpanText.textContent = todoField.value;
  newSpanText.className = "break-words";

  // 將創建的span, button元素依序加入到新創的的li元素內(子元素)
  newLi.append(newSpanIcon, newSpanDone, newSpanText, newBtn);

  // 將創建的li元素加入到ul元素內的最下面, 嘗試使用其他的method:insertAdjacentElement()
  // https://developer.mozilla.org/zh-CN/docs/Web/API/Element/insertAdjacentElement
  $todolist.insertAdjacentElement("beforeend", newLi);

  // 清除 user 輸入內容,並將游標定位到 user 輸入欄位
  $todoField.value = "";
  $todoField.focus();

  showHiddenTodo();
}

// 選取到目前點擊的button的父元素li,把li刪除
function delTodo() {
  event.target.closest("li").remove();
  save();
  showHiddenTodo();
}

// 匯出純文字
function exportText() {
  let exportContent = "今日待辦:\n---------------\n";
  let num = 1; // 匯出時的項目編號

  // document.querySelector("#todolist").children 表示ul中有多少個li
  // document.querySelectorAll("#todolist > li") 效果一樣
  for (let item of document.querySelectorAll("#todolist > li")) {
    // 取得每筆待辦事項的priority,判斷匯出時是否要加上*或**
    const prioritySymbol =
      item.dataset.priority == "important"
        ? "*"
        : item.dataset.priority == "urgent"
        ? "**"
        : "";

    // 跑一次迴圈就在要輸出結果的字串中加入一筆待辦事項
    exportContent +=
      num.toString() +
      ". " +
      prioritySymbol +
      item.querySelectorAll("span")[2].textContent +
      prioritySymbol +
      "\n";

    num++; // 跑一次迴圈,編號就+1 → 1, 2, 3.....
    console.log(exportContent); // 可以看看每跑一次迴圈後的輸出結果
  }

  return alert(exportContent);
}

// 依照選擇一般、重要、緊急,切換新增待辦區塊的主題顏色
function addTodotheme() {
  // 設定一般、重要、緊急對照的主題顏色
  const themeColors = {
    normal: "sky",
    important: "orange",
    urgent: "red"
  };

  // 依照選取的value取得主題顏色
  let themeColor = themeColors[document.querySelector("#category").value];

  for (let item of ["#category", "#todoField", "#addTodoBtn"]) {
    // 先刪除既有主題顏色的class,不管有或沒有,一律全刪
    for (let color of Object.values(themeColors)) {
      document
        .querySelector(item)
        .classList.remove(`border-${color}-600`, `bg-${color}-600`);
    }

    // 加入目前選取的主題顏色的class
    document
      .querySelector(item)
      .classList.add(
        `${item != "#addTodoBtn" ? "border" : "bg"}-${themeColor}-600`
      );
  }
}

// 待辦事項完成
function todoDone() {
  if (!event.target.classList.replace("bg-gray-300", "bg-rose-600")) {
    event.target.classList.replace("bg-rose-600", "bg-gray-300");
    event.target.closest("li").querySelectorAll("span")[1].style.display =
      "none";
    event.target.closest("li").querySelectorAll("span")[2].className = "";
  } else {
    event.target.closest("li").querySelectorAll("span")[1].style.display =
      "block";
    event.target.closest("li").querySelectorAll("span")[2].className =
      "text-slate-400 line-through";
  }
}

// 判斷有無待辦事項,顯示或隱藏待辦事項區塊
function showHiddenTodo() {
  if (document.querySelectorAll("#todolist > li").length) {
    document.querySelector("#todoBox").style.display = "block";
  } else {
    document.querySelector("#todoBox").style.display = "none";
  }
}

// 儲存到Local Storage
function save() {
  const $todoItems = document.querySelectorAll("#todolist > li");

  todoItems = [...$todoItems];

  const data = todoItems.map((todoItem) => {
    return {
      priority: todoItem.dataset.priority,
      itemStyle: todoItem.className,
      todoDoneIcon: todoItem.querySelectorAll("span")[0].className,
      todoDone: todoItem.querySelectorAll("span")[1].className,
      todoDoneDispay: todoItem.querySelectorAll("span")[1].style.display,
      textStyle: todoItem.querySelectorAll("span")[2].className,
      text: todoItem.querySelectorAll("span")[2].textContent
    };
  });

  localStorage.setItem("data", JSON.stringify(data));
  alert("儲存成功!");
}

function init() {
  const $todolist = document.querySelector("#todolist");

  if (localStorage.getItem("data")) {
    const data = JSON.parse(localStorage.getItem("data"));

    $todolist.innerHTML = data
      .map((item) => {
        return `<li data-priority="${item.priority}" class="${item.itemStyle}"><span class="${item.todoDoneIcon}" onclick="todoDone()">&#10004;</span><span class="${item.todoDone}" style="display: ${item.todoDoneDispay};">已完成</span><span class="${item.textStyle}">${item.text}</span><button class="text-slate-300 font-semibold tracking-widest px-3 py-1 bg-rose-600 rounded-md hover:bg-opacity-70 ml-auto" onclick="delTodo()">刪除</button></li>`;
      })
      .join("");
  }

  showHiddenTodo();
}

init();

              
            
!
999px

Console