<香港科技大学html+css+js课堂笔记>week3--DOM模型基础

来源:互联网 发布:拳击直播软件 编辑:程序博客网 时间:2024/05/23 23:48

1.DOM含义:

Document Object Model;


2.Eg:

<!DOCTYPE html>
<html>
<head>
    <title>A Simple Web Page</title>
    <meta name="author" content="David Rossiter">
</head>
<body>
    <h1>My Web Page</h1>
    <p>This web page is so awesome!</p>
</body>
</html>



3.whitespace:

A COMPARISON:
1] <body><p>Hello.</p>

<body><p>之间没有空格node

2] <body>
 <p>Hello.</p>

<body><p>之间没有空格节点


4.NODE RELATIONSHIPS:

1>怎样找到节点的位置:

function handleClick(event) {
  event.stopPropagation();
  var node = event.target
  var thisPath = node.nodeName;
  while (node.parentNode) {
    node = node.parentNode;
    thisPath = node.nodeName + " > " + thisPath;
  }
  alert(thisPath);
}

2>为每个节点注册触发器:

// Register the click event handler for all nodes
function attachHandler(node) {
  if(node == null) return;
  node.onclick = handleClick;
        
  for (var i = 0; i < node.childNodes.length; ++i)
    attachHandler(node.childNodes[i]);
} 利用递归!


5.定位节点位置:

1>使用精确的地址:

document.childNodes[0].childNodes[2].childNodes[1].style.color;

2>getElementsByTagName("body"):

document.getElementsByTagName("h2")[0].style.color;

3>getElementById("num_text");

document.getElementById("cute_text").style.color.

4>setAttribute("style", "color:red"):

document.getElementsByTagName("h2")[0].setAttribute("style", "color:yellow");


6.加入节点:

1>createElement("hr") //<hr>表示一条横线。

result = document.createElement("div");

Eg:

newItem = document.createElement("hr");
destParent = document.getElementsByTagName("body")[0];
destParent.insertBefore(newItem, destParent.firstChild);

2>appendChild(....):

result=document.createTextNode("This is dynamically added Text!");      
document.getElementById("my_text").appendChild(result);


7.删除节点:

1>三种方式:(删除某一个节点)

1) var the_node=document.getElementById("firstP");
the_node.parentNode.removeChild(the_node); 
2) var the_node=document.getElementsByTagName("p")[0];
the_node.parentNode.removeChild(the_node); 
3) var the_parent=document.getElementById("theBody");
the_parent.removeChild(the_parent.firstChild);

2>删除网页中的所有节点:

var theNode = document.getElementById("theBody");
while (theNode.firstChild)   // While there is a child
    theNode.removeChild(theNode.firstChild);.

3>复制(节点标签)或(节点标签与内容):

the_node.clone();与 the_node.cloneNode(false)效果相同---复制节点标签。

the_node.clone(true);---复制节点标签与内容。


0 0
原创粉丝点击