Native js realizes Todolist (to-do) local storage


Insert picture description here

demand

First clarify the functions that need to be implemented

  1. Enter the content, click the add button or press Enter to add to-do items
  2. Click the delete button to delete
  3. The content is saved locally, and the list is still there after refreshing and restarting

Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
    * {
     
     
        margin: 0;
        padding: 0;
        border: 0;
        outline: none;
        list-style: none;
        box-sizing: border-box;
    }
    body{
     
     
        background-color: #F48C78;
        overflow-x: hidden;
        transform: scale(1.2);
    }
    #container{
     
     
        width: 300px;
        margin: 80px auto 0 auto;
        padding: 10px;
        min-height: 450px;
        background-color: #2F3D4A;
        box-shadow: 0px 3px 10px #8F5246,3px 0px 10px #8F5246;
        border-radius: 10px;
    }
    #container h1{
     
     
        color: #FCFFFF;
        width: 85px;
        margin: 30px auto;
    }
    #input {
     
     
        font-size: 0;   
        position: relative;
    }
    #input input{
     
     
        width: 80%;
        height: 30px;
        margin-left: 9%;
        border-radius: 15px;
        padding: 5px 10px;
    }
    #input input::-webkit-input-placeholder{
     
      /* chrome safari*/
        color: #AFB2B9;
        text-align: center;
    }
    #input input::-moz-placeholder{
     
      /* 火狐获取placeholder*/
        color: #AFB2B9;
        text-align: center;
    }
    #input button{
     
     
        width: 45px;
        height: 30px;
        border-radius: 0 15px 15px 0;
        background-color: #F48C78;
        position: absolute;
        right: 30px;
        cursor: pointer;
        opacity: 0;
        transition: all 0.5s 0.1s;
        visibility: hidden;
        color: #fff;
    }
    #input input:focus + button, #input button:hover{
     
     
        opacity: 1;
        visibility: visible;
    }
    #input button:hover{
     
     
        background-color: #CD4F35;
    }
    ul{
     
     
        margin: 30px 0;
    }
    ul li{
     
     
        width: 224px;
        margin:  10px 0 0 9%;
        color: #FCFFFF;
        background-color: #283140;
        font-weight: 600;
        padding: 5px 10px;
        border-radius: 10px;
    }
    ul li:hover{
     
     
        background-color: #455878;
        transition: all 0.4s ;
    }

    .removebtnContainer{
     
     
        margin: 4px 5px 0 0;
        float: right;
        border-radius: 50%;
        width: 13px;
        height: 13px;
        border: solid #FD8263;
        position: relative;
        top: 50%;
        transition: all 0.2s ;
        cursor: pointer;
    }
    .removebtnContainer:hover{
     
     
        background-color: #FD8263;
    }
    </style>
</head>
<body>
    <!-- html部分属实简单 -->
    <div id="container">
        <h1>Todos</h1>
        <div id="input">
            <input type="text" id="content" placeholder="别玩了懒狗" onfocus="this.placeholder = ''" onblur="this.placeholder = '别玩了懒狗'">
            <!-- placeholder 内容自己改 -->
            <button>add</button>
        </div>

        <ul id="ul"></ul>
    </div>

    <script>
        let todoList = document.getElementsByTagName('ul')[0]; 
        let inputElement = document.getElementById('content');
        let buttonElement = document.getElementsByTagName('button')[0];
        let todos = JSON.parse(localStorage.getItem('todos')) || [];  // todos数组保存待办项 
        
        function addNew(content){
     
     
            let item = document.createElement('li');
            item.innerText = content; 
            addNewButton(item); 
            todoList.appendChild(item);

            todos.push(content);
            save();
        }
        function addNewButton(item){
     
     
            let container = document.createElement('div');
            container.className = 'removebtnContainer';
            item.appendChild(container);
        }
        function save(){
     
     
            localStorage.setItem('todos',JSON.stringify(todos)); // 将数组转为字符串并储存在本地
        }
        function reLoad(){
     
       
            
            todos.forEach((content) => {
     
     
                let item = document.createElement('li');
                item.innerText = content;
                addNewButton(item);
                todoList.appendChild(item);
            });
        }

        function reMove(item){
     
     
            item.parentNode.remove(); 
            todos.forEach((content, index) => {
     
              
                if(item.parentNode.innerText.trim() == content){
     
     
                    todos.splice(index, 1);  // splice方法 删除index开始的 1项
                }
            })

            save();
        }

        /* ↑ 函数声明
        -------------------------------------------------------------------------
        事件、执行 ↓                                                              */
        
        reLoad(); //从本地载入

        /*两种方式添加待办项*/
        //鼠标点击添加
        buttonElement.addEventListener('click', () =>{
     
     
            if(inputElement.value){
     
     
                addNew(inputElement.value.trim());
                inputElement.value = '';
            }
        },false)
        //键盘回车添加
        inputElement.addEventListener('keyup', (event) =>{
     
     
            console.log(event); 
            if(event.keyCode == 13 && inputElement.value){
     
       //回车 keyCode === 13
                addNew(inputElement.value.trim());
                inputElement.value = '';
            }
        })

        //点击删除
        todoList.addEventListener('click',(event)=>{
     
     
            if(event.target.className == 'removebtnContainer'){
     
     
                reMove(event.target);
            }
        },false)
    </script>
</body>

</html>

The js part is not long, and the logic is clear.
CSS is the most difficult

Partial explanation

Local storage

localStorage tutorial
Use localStorage to store locally and read
it every time you open the page. Because localStorage stores data in string form, so use JSON to convert the array to string format

localStorage.setItem('todos',JSON.stringify(todos));
Insert picture description here

Add to

addEventListenerPass the event object to the subsequent processing function

        inputElement.addEventListener('keyup', (event) =>{
    
      //此处event为addEventListener传入
            console.log(event); 
            if(event.keyCode == 13 && inputElement.value){
    
      //回车 keyCode === 13
                addNew(inputElement.value.trim());
                inputElement.value = '';
            }
        })

Array method

forEach, splice see an array of methods

bug

There is currently a bug in deletion, and elements with the same content will be deleted together
. The drawbacks of retrieval by content are so,
I haven't thought of a good solution

Guess you like

Origin blog.csdn.net/S_aitama/article/details/107724017