javascript實現留言板功能
阿新 • • 發佈:2020-02-10
本文例項為大家分享了javascript實現留言板功能的具體程式碼,供大家參考,具體內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box{ /*設定最外層盒子*/ width: 600px; border: 1px solid #aaa; padding: 20px 10px; margin: 100px auto; } #plTxt{ /*設定文字域*/ width: 450; resize: none;/*防止使用者拖拽*/ } .box ul{ /*將ul列表去除前面的點*/ list-style: none; } .box ul li{ /*設定li中的評論文字樣式*/ width: 450px; line-height: 30px; border-bottom: 1px dotted #aaa; margin-left: 50px; } .box ul li a{ /*將刪除的樣式更改顏色,向右浮動,沒有下劃線*/ color: orange; float: right; text-decoration: none; } .box ul li .time{ /*將li中的時間改為向右浮動和改顏色*/ color: #4f0; float: right; } </style> <script> window.onload = function(){ function $(id){ return document.getElementById(id); } var ul=document.createElement('ul'); //建立ul標籤 $('pl').appendChild(ul); //把ul標籤放在div裡面 $('btn').onclick = function (){ var txt = $('plTxt').value; //此時不能用$('plTxt').innerHTML,成對的標籤使用innerHTNL,獲得裡面文字; if(txt.length==0){ //判斷輸入為空的情況; alert('不能發表為空的評論'); }else{ var li=document.createElement('li'); //建立li標籤 ul.appendChild(li); // li新增為ul的子標籤 txt = txt+ "<a href='javascript:void(0)'>刪除</a>" + "<span class='time'>" + new Date().toLocaleTimeString() + "</span>"; li.innerHTML = txt; //將文字賦給li標籤中顯示 var dels =document.getElementsByTagName('a'); //獲取所有標籤a的id存到陣列中 for(var j=0; j<dels.length; j++){ dels[j].onclick=function(){ //將所有a標籤設定點選事件 //刪除當前評論,就是刪除當前“刪除”所在超連結的li ul.removeChild(this.parentNode); } } } } } </script> </head> <body> <div class="box" id="pl"> <span>發表評論:</span> <textarea id="plTxt" cols="30" rows="10"></textarea> <input type="button" value="評論" id="btn" > </div> </body> </html>
新增加的文字放在後面,將程式碼中的
ul.appendChild(li); //(li新增為ul的子標籤,每次都放在末尾)換成: ul.insertBefore(li,ul.children[0]); //——這行程式碼為插入,將當前的li標籤,插在ul的第一個子標籤之前,即新的li標籤每次都插入在最前面。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。