您好,登錄后才能下訂單哦!
小編給大家分享一下javascript實現(xiàn)留言板功能的方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
具體內(nèi)容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box{ /*設(shè)置最外層盒子*/ width: 600px; border: 1px solid #aaa; padding: 20px 10px; margin: 100px auto; } #plTxt{ /*設(shè)置文本域*/ width: 450; resize: none;/*防止用戶拖拽*/ } .box ul{ /*將ul列表去除前面的點*/ list-style: none; } .box ul li{ /*設(shè)置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'); //創(chuàng)建ul標簽 $('pl').appendChild(ul); //把ul標簽放在div里面 $('btn').onclick = function (){ var txt = $('plTxt').value; //此時不能用$('plTxt').innerHTML,成對的標簽使用innerHTNL,獲得里面文字; if(txt.length==0){ //判斷輸入為空的情況; alert('不能發(fā)表為空的評論'); }else{ var li=document.createElement('li'); //創(chuàng)建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存到數(shù)組中 for(var j=0; j<dels.length; j++){ dels[j].onclick=function(){ //將所有a標簽設(shè)置點擊事件 //刪除當前評論,就是刪除當前“刪除”所在超鏈接的li ul.removeChild(this.parentNode); } } } } } </script> </head> <body> <div class="box" id="pl"> <span>發(fā)表評論:</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標簽每次都插入在最前面。
看完了這篇文章,相信你對“javascript實現(xiàn)留言板功能的方法”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。