Blogger Information
Blog 40
fans 2
comment 1
visits 39070
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
10.JavaScript-留言板-2019年01月17号
万物皆对象
Original
608 people have browsed it

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1.ToList留言板</title>
    <style>
        *{margin: 0;padding: 0;}
        div{
            width: 200px;height: 200px;
            background: lightblue;
        }
    </style>
</head>
<body>
    <!-- 
        重点:↓
        1.文档节点:document
        2.元素节点:Element
        3.文本节点:Text
        4.需要牢记的属性:
            children = 子元素;childNode = 子节点;
            childElementCount = 计算子元素的数量;
            keyCode = 键盘码;firstElementChild = 第一个子元素
        5.需要牢记的方法:
            querySelector('标签名称') = 查找选择器;
            document.getElementsByTagName() = 通过标签名获取元素;
            appendChild() = 添加子元素;insertBefore() = 插入最前;
            focus() = 获取焦点; removeChild() = 移除子元素;
            document.createElem() = 创建元素;
    -->
    <h3>请写下你的留言:</h3>
    <input type="text" style="width:196px;height:30px;">
    <div>
        <ul></ul>
    </div>
</body>
</html>
<script>
    // 第一步:获取input标签和ul标签并给input设置焦点
    var comment = document.querySelector('input');
    var ul      = document.getElementsByTagName('ul')[0];
    comment.focus(); // 给input设置焦点

    // 第二步:当input输入值并按下回车键后创建li标签并将input的值添加到li里面
    comment.onkeydown = function(e){
        //console.log(e.keyCode);
        if(e.keyCode === 13){
            var li = document.createElement('li');
            li.innerHTML = comment.value + '<a href="javascript:;" onclick="del(this)">'+'删除'+'</a>';
            //console.log(li);

            // 第三步:判断ul下面是否有子元素 有就新增到现有的第一个子元素前面,没有就直接新增
            if(ul.childElementCount === 0){
                ul.appendChild(li);
            }else{
                var first = ul.firstElementChild;
                console.log(first);
                ul.insertBefore(li,first);
            }

            // 按下回车后清空input的值,并重新获取焦点
            comment.value = '';
            comment.focus();
        }
    }

    // 第四步:留言删除
    function del(ele){
        if(confirm('确定要删除吗?')){
            var li = ele.parentNode;
            li.parentNode.removeChild(li);
        }
    }
</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例

666.jpg

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post