1. 程式人生 > >JS的DOM操作元素示例1--刪除新增元素

JS的DOM操作元素示例1--刪除新增元素

-- 刪除新增元素
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Adding and Removing Elements</title>
    <style>
        .overlay{
            background-color: #000;
            opacity: 0.5;
            filter: alpha(opacity=50);
            position
: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; } .overlaymsg{ position: absolute; background-color: yellow; padding: 10px; width: 200px; height: 200px; font-size: 2em; z-index
: 11; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; } </style> </head> <body> <p>Existing material.</p> <script> function displayPopup(){ //建立覆蓋並將其附加到頁面 var overplay = document.createElement
("div"); //建立元素 overplay.setAttribute("id","overlay"); //建立設定元素 overplay.setAttribute("class","overlay"); document.body.appendChild(overplay); //建立影象並將其附加到頁面 var msg = document.createElement("div"); var txt = document.createTextNode("Please join our mailing list!(Click to close.)"); msg.appendChild(txt); msg.setAttribute("id","msg"); msg.setAttribute("class","overlaymsg"); //css是如何影響 元素的js動作的表現的,這行的錯誤,會影響下一行 //單擊以恢復頁面 msg.onclick = restore; //設定 動作觸發 //將訊息附加到覆蓋 document.body.appendChild(msg);//新增到頁面 } //將頁面恢復正常,removeChild() 刪除元素 function restore(){ console.log("*****************"); document.body.removeChild(document.getElementById("overlay")); document.body.removeChild(document.getElementById("msg")); } window.onload = function(){ displayPopup(); } </script> </body> </html>