2012年8月28日 星期二

javascript DOM 新增、刪除

javascript DOM 新增、刪除 操作

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DOM 新增、刪除</title>
<script>
window.onload = function(){
//add element
document.getElementById('addDiv').onmousedown = function(){
var node = document.createElement("div");  //建立一個元素  
    node.style.width = "50px"; //DIV 寬度
    node.style.height = "50px"; //DIV 高度
    node.style.backgroundColor = "#FF0000"; //背景色
    node.style.border = "solid"; //邊框為實線
    node.style.borderWidth = "1px"; //邊框寬度
    node.style.borderColor = "#CCCCCC"; //邊框色彩
    //node.setAttribute("id","myDiv");  //可以用來設定元素屬性
document.body.appendChild(node);  //把元素加到body元素裡面
};

//remove element
document.getElementById('removeDiv').onmousedown = function(){
var nodes =  document.getElementsByTagName('div'); //傳回DIV element的array
//console.log(nodes);
//remove last div
if(nodes && nodes.length > 0){
//console.log(nodes[nodes.length-1]) //google瀏覽器使用
document.body.removeChild(nodes[nodes.length-1]); //刪除最後面的DIV
}
};
}
</script>
</head>
<body>
<input id="addDiv" type="button" value="add Div"/>
<input id="removeDiv" type="button" value="remove Div"/>
</body>
</html>

沒有留言:

張貼留言