综合案例:微博发布新鲜事

 1 <!doctype html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <style>
 7         *{
 8             margin: 0;
 9             padding: 0;
10         }
11         #box{
12             width: 600px;
13             border: 1px solid black;
14             padding:30px 0;
15             margin: 100px auto;
16         }
17         textarea{
18             resize: none;
19         }
20         ul{
21             list-style: none;
22         }
23         li{
24             width: 400px;
25             margin: 0 80px;
26             border-bottom: 1px dashed #aaa;
27         }
28         li a{
29             float: right;
30         }
31     </style>
32 </head>
33 <body>
34 <div id="box">
35     微博发布:
36     <textarea name="" id="txt" cols="60" rows="10"></textarea>
37     <button id="dist">发布</button>
38 </div>
39 <script>
40     // 获取文本节点和发布按钮节点
41     let txt = document.getElementById('txt');
42     let btn = document.getElementById('dist');
43     //创建并插入ul
44     let ul = document.createElement('ul');
45     txt.parentNode.appendChild(ul);
46     // 给发布按钮绑定单击事件的事件处理程序
47     btn.addEventListener('click',function () {
48         if (!txt.value){// 如果为空则不继续执行
49             alert( '输入不能为空!');
50             return;
51         }
52         // 创建li节点并装入内容,然后插入
53         let li = document.createElement('li');
54         li.innerHTML=txt.value+'<a href="javascript:void(0);">删除</a>';
55         ul.insertBefore(li,ul.children[0]);
56         
57         //清空文本框内容
58         txt.value='';
59         //给刚加入的li节点内的a标签绑定事件处理程序
60         li.getElementsByTagName('a')[0].addEventListener('click',function () {
61             ul.removeChild(this.parentNode);
62         })
63     })
64 </script>
65 </body>
66 </html>

猜你喜欢

转载自www.cnblogs.com/ustc-yy/p/12074179.html