todolist项目可谓是前端学员的一个必修项目,各式各样的前端框架都可以从这个简单的小项目练起,在使用框架开发两年的时间呢,最近感觉对原生js的一些用法生疏的很,便借用这个基础小项目复习了一下js语言,同时也适用于刚接触前端的同学,下面就是一些示例图和代码,感兴趣的小伙伴来看看吧。
vue3.0 版本todo list案例点此查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDoList</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
}
#listArea {
width: 300px;
height: max-content;
margin: 10px auto;
}
li {
width: 100%;
height: 50px;
line-height: 50px;
border: 3px dotted skyblue;
margin-bottom: 10px;
padding-left: 10px;
color: blue;
display: flex;
align-items: center;
}
.text {
margin-left: 10px;
}
.userInput {
width: max-content;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.noData {
width: 300px;
height: 300px;
line-height: 300px;
margin: 10px auto;
border: 3px dotted skyblue;
text-align: center;
font-size: 20px;
color:rgb(220, 167, 241);
}
.active {
color: red;
}
#inputBox {
width: 300px;
margin: auto;
display: block;
margin-right: 10px;
}
h1 {
text-align: center;
margin: auto;
color: aqua;
}
</style>
</head>
<body>
<h1>茜氏男友出品</h1>
<div class="userInput">
<input type="text" id="inputBox" placeholder="请输入待办事项" ref="inpRef">
<button>添加</button>
</div>
<ul id="listArea">
</ul>
<script>
const listArea = document.getElementById('listArea') // 列表容器
const inputBox = document.getElementById('inputBox') // 输入框
let listData = [] // 列表
// 页面加载完成
window.onload = () => {
listArea && renderList()
}
// 页面点击事件
window.addEventListener('click',(e) => {
if(e.target.nodeName === 'BUTTON') {
inputWrite()
return
}
if(e.target.type === 'checkbox') {
checkItem(e.target.parentNode.getAttribute('key'))
}
})
// 渲染列表
function renderList() {
listArea.innerHTML = ''
if(listData.length > 0) {
listData.forEach((item, index) => {
let LI = document.createElement('li')
LI.setAttribute('key',item.id)
LI.setAttribute('class',item.is_finish ? 'active' : '')
LI.innerHTML = `
<input type="checkbox" ${item.is_finish && 'checked'} />
<p class="text">${index+1}、${item.text} ${item.is_finish ? '已完成' : '待办'}</p>`
listArea.appendChild(LI)
})
return
}
listArea.innerHTML = '<div class="noData">今日小目标,记录一下吧</div>'
}
// 输入待办事项
function inputWrite() {
if(inputBox.value.trim() === '') {
alert('输入不可为空')
inputBox.value = ''
return
}
let obj = {
id: new Date().getTime(),
text: inputBox.value,
is_finish: false
}
listData.unshift(obj)
inputBox.value = ''
renderList()
}
// 选中状态
function checkItem(id) {
const ind = listData.findIndex(item => item.id === Number(id))
if(ind !== -1) {
listData[ind].is_finish = !listData[ind].is_finish
renderList()
}
}
</script>
</body>
</html>