JS-待辦事項管理-第一課作業

認識 DOM 樹、新增元素

by igorrrrr

HTML

<div class="app">
      <div class="container">
        <h1>Todo List</h1>
        <div class="todoWrap">
          <div class="input-wrap">
            <input type="text" id="input" placeholder="請輸入待辦事項..." />
            <button class="add-btn" onclick="addList()">+</button>
          </div>
        </div>
        <div class="container">
          <ul id="list">
            <li><span>ex代辦事項:買外套</span></li>
          </ul>
        </div>
      </div>
    </div>

CSS

* {
        padding: 0;
        margin: 0;
      }
      ul li {
        list-style: none;
        text-align: left;
      }
      body {
        background-color: #bfc2e3;
        /* background-image: linear-gradient(0deg, #d78383, #bfc2e3); */
      }
      .app {
        font-family: "Segoe UI", "Open Sans", "Helvetica Neue", sans-serif;
        width: 100%;
        /* height: 100vh; */
      }
      .container {
        margin: 0 auto;
        width: 300px;
        text-align: center;
      }
      .add-btn {
        background-color: #f0ecfc;
        background-image: linear-gradient(315deg, #f0ecfc 0%, #c797eb 74%);
        color: #fff;
        overflow: hidden;
        line-height: 18px;
        width: 25px;
        height: 25px;
        padding: 0;
        border: none;
        border-radius: 5px;
      }
      .add-btn::after {
        position: absolute;
        content: "";
        right: 0;
        bottom: 0;
        background: #c797eb;
      }
      .add-btn:hover {
        box-shadow: 4px 4px 6px 0 rgba(255, 255, 255, 0.5),
          -4px -4px 6px 0 rgba(116, 125, 136, 0.5),
          inset 4px 4px 6px 0 rgba(255, 255, 255, 0.2),
          inset 4px 4px 6px 0 rgba(0, 0, 0, 0.4);
      }
      .todoWrap #input {
        height: 18px;
        border-radius: 80px;
        outline: 0;
        border: 1px solid rgb(255, 255, 255, 0.4);
        caret-color: transparent;
        background-color: transparent;
        padding: 5px 5px 5px 8px;
        font-size: 18px;
      }
      .todoWrap #input:focus {
        border: 1px rgb(255, 255, 255, 0.4) solid;
        box-shadow: 1px 2px 1px rgb(255, 255, 255, 0.4);
      }

      /* 設定代辦清單的樣式 */
      .container #list {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
      }
      .container #list li span {
        display: inline-block;
        background-color: #f0ecfc;
        height: 20px;
        font-size: 18px;
        margin: 5px;
        padding: 5px;
       ...

JavaScript

function addList() {
        let input = document.querySelector("#input");
        let inputValue = input.value;
        //將Todo的資料顯示在下方
        let todoContent = document.createElement("li");
        let todoSpan = document.createElement("span");
        todoSpan.textContent = inputValue;
        let list = document.getElementById("list");
        list.append(todoContent);
        todoContent.append(todoSpan);
        console.log(todoSpan);
      }