50 天学习 50 个项目 - HTMLCSS and JavaScript
day49-Todo List(待办事项列表)
效果
index.html
<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" /> < meta name = " viewport" content = " width=device-width, initial-scale=1.0" /> < title> Todo List</ title> < link rel = " stylesheet" href = " style.css" />
</ head> < body> < h1> todos</ h1> < form id = " form" > < input type = " text" class = " input" id = " input" placeholder = " Enter your todo" autocomplete = " off" > < ul class = " todos" id = " todos" > </ ul> </ form> < small> 左键单击以切换完成。< br> 右键单击可删除待办事项</ small> < script src = " script.js" > </ script>
</ body> </ html>
style.css
@import url ( 'https://fonts.googleapis.com/css2?family=Poppins:wght@200;400&display=swap' ) ; * { margin : 0; padding : 0; box-sizing : border-box;
} body { background-color : #f5f5f5; color : #444; font-family : 'Poppins' , sans-serif; display : flex; flex-direction : column; align-items : center; justify-content : center; height : 100vh; margin : 0;
}
h1 { color : aqua; font-size : 10rem; text-align : center; opacity : 0.5;
}
form { box-shadow : 0 4px 10px rgba ( 0, 0, 0, 0.8) , 4px 0px 10px rgba ( 255, 255, 255, 0.9) ; max-width : 100%; width : 400px;
}
.input { border : none; color : #444; font-size : 2rem; padding : 1rem 2rem; display : block; width : 100%;
} .input::placeholder { color : #d5d5d5;
} .input:focus { outline-color : aqua;
}
.todos { background-color : #fff; list-style-type : none;
}
.todos li { border-top : 1px solid #e5e5e5; cursor : pointer; font-size : 1.5rem; padding : 1rem 2rem;
}
.todos li.completed { color : #b6b6b6; text-decoration : line-through;
}
small { color : #b5b5b5; margin-top : 1rem; text-align : center;
}
script.js
const form = document. getElementById ( 'form' )
const input = document. getElementById ( 'input' )
const todosUL = document. getElementById ( 'todos' )
const todos = JSON . parse ( localStorage. getItem ( 'todos' ) )
if ( todos) { todos. forEach ( todo => addTodo ( todo) )
}
form. addEventListener ( 'submit' , ( e ) => { e. preventDefault ( ) addTodo ( )
} )
function addTodo ( todo ) { let todoText = input. valueif ( todo) { todoText = todo. text} if ( todoText) { const todoEl = document. createElement ( 'li' ) if ( todo && todo. completed) { todoEl. classList. add ( 'completed' ) } todoEl. innerText = todoTexttodoEl. addEventListener ( 'click' , ( ) => { todoEl. classList. toggle ( 'completed' ) updateLS ( ) } ) todoEl. addEventListener ( 'contextmenu' , ( e ) => { e. preventDefault ( ) todoEl. remove ( ) updateLS ( ) } ) todosUL. insertBefore ( todoEl, todosUL. children[ 0 ] ) input. value = '' updateLS ( ) }
}
function updateLS ( ) { let todosEl = document. querySelectorAll ( 'li' ) const todos = [ ] todosEl. forEach ( todoEl => { todos. push ( { text : todoEl. innerText, completed : todoEl. classList. contains ( 'completed' ) } ) } ) localStorage. setItem ( 'todos' , JSON . stringify ( todos) )
}