JSFiddle - React, Tailwind, and code Playground
HTML
<h1 style="text-align: center;">JavaScript 系列二:第1課 ── 認識 DOM 樹、新增元素</h1>
<div class="box">
<h1 class="title">待辦事項</h1>
<div class="create">
<input type="text" name="memo" id="memo" placeholder="待辦事項">
<button id="submit" onclick="create()">新增</button>
</div>
<ul class="todoList" id="todoList">
</ul>
</div>
CSS
* {
padding: 0;
margin: 0;
list-style-type: none;
}
.box {
width: 300px;
/* 30px用來方便觀察 */
margin: 30px auto 0;
box-sizing: border-box;
padding: 20px;
border-radius: 20px;
border: 5px solid rgba(45, 12, 88, 1);
}
.box .title {
padding: 10px 0;
font-size: 24px;
font-weight: 900;
color: rgba(45, 12, 88, 1);
text-align: center;
}
.box .create {
/* 消除input button 為display: inline-block;的空白字元 */
font-size: 0;
}
.box .create input,
.box .create button {
display: inline-block;
vertical-align: middle;
box-sizing: border-box;
line-height: 20px;
padding: 10px;
border: 2px solid #ccc;
}
.box .create input {
outline: none;
border-right: none;
border-radius: 30px 0 0 30px;
}
.box .create button {
border-left: none;
border-radius: 0 30px 30px 0;
cursor: pointer;
font-weight: 900;
}
.box .create button:hover {
color: #fff;
background-color: #000;
transition: 0.3s;
}
.box .todoList li {
font-size: 18px;
text-align: justify;
padding: 20px;
word-break: break-word;
}
.box .todoList li + li {
border-top: 1px solid #ccc;
}
JavaScript
function create() {
// 取得要新增的待辦事項文字
let memos = document.getElementById("memo");
let memoInput = memos.value;
let memo = memoInput.trim();
if (memo == "") {
alert("請輸入待辦事項");
return;
}
// 取得待辦列表物件
let todoList = document.getElementById("todoList");
// 建立新的子列表
let list = document.createElement("li");
// 將要新增的代辦事項填入新建立的子列表
list.textContent = memo;
todoList.append(list);
// 新增之後,清除input已輸入的文字
memos.value = "";
}