JS實現仿微博釋出
阿新 • • 發佈:2019-01-30
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ padding: 0; margin: 0; } ul { list-style: none; } .box { width: 550px; border: 1px solid #333; padding: 10px; } textarea{ width: 400px; height: 150px; resize: none; } li { padding-left: 80px; border-bottom: 1px dashed #ccc; } li a { float: right; } </style> </head> <body> <div class="box" id="box"> 微博釋出:<textarea name="" id="txt" cols="30" rows="10"></textarea><button id="btn">釋出</button> </div> <script> var oBox = document.getElementById("box"); var btn = document.getElementById('btn'); var txt = document.getElementById("txt"); var oUl = document.createElement("ul"); oBox.appendChild(oUl); btn.onclick = function(){ if (txt.value=='') { alert("輸入點內容吧!"); return; }; //判斷是否有輸入; var oLi = document.createElement("li"); //建立一個新的li元素 oLi.innerHTML = txt.value + "<a href='#'>刪除</a>"; //設定li的內容為文字框中的內容; var lis = oUl.children; //找到li中所有的li if(lis.length == 0){//如果長度是0;則在他的前邊加 oUl.appendChild(oLi); } else { oUl.insertBefore(oLi,lis[0]); } txt.value = ''; var as = oBox.getElementsByTagName("a"); for (var i = 0; i < as.length; i++) { as[i].onclick = function(){ this.parentNode.style.display = "none"; }; }; }; </script> </body> </html>