简单版发布留言案例

案例分析:

1.点击按钮之后就动态创建一个 li;

2.创建 li 的同时,把文本域里面的值通过 innerHTML 赋值给 li;

3.如果想要新的留言后面显示就用 appendChild ,如果想要在前面显示就用 insertBefore 。

效果:

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>简单版发布留言</title>
 6         <style>
 7             *{
 8                 margin: 0;
 9                 padding: 0;
10             }
11             body{
12                 padding: 100px 300px;
13             }
14             textarea{
15                 width: 350px;
16                 height: 200px;
17                 resize: none;
18                 overflow: auto;
19             }
20             li{
21                 list-style-type: none;
22                 width: 400px;
23                 border: 1px solid gray;
24                 background-color: rgb(218, 248, 255);
25                 margin: 3px 0;
26                 padding: 3px;
27                 font-size: 10px;
28             }
29         </style>
30     </head>
31     <body>
32         <!--
33             placeholder属性规定描述文本区域内预期值的简短提示
34             cols 和 rows 属性来规定 textarea 的尺寸,不过更好的办法是使用 CSS 的 height 和 width 属性
35         -->
36         <textarea name="" id=""  placeholder="请输入您想要发布的内容"></textarea>
37         <button>发布</button>
38         <ul>
39 
40         </ul>
41     </body>
42     <script>
43         //1.获取元素
44         var btn=document.querySelector("button");
45         var text=document.querySelector("textarea");
46         var ul=document.querySelector("ul");
47         //2.注册事件
48         btn.onclick=function(){
49             if(text.value==""){
50                 alert("您没有输入内容");
51             }
52             else{
53                 //(1)创建元素
54                 var li=document.createElement("li");
55                 //先有li才能赋值
56                 li.innerHTML=text.value;
57                 //(2)添加元素
58                 ul.insertBefore(li,ul.children[0]);
59                 //删除文本域中的文字
60                 text.value="";
61             }
62         }
63     </script>
64 </html>
原文地址:https://www.cnblogs.com/cy1227/p/12500040.html