javascript之DOM技术(二)
2010-09-14 13:06:48 来源:WEB开发网var op1=document.getElementById("p1");
oRange1.selectNode(op1);
oRange2.selectNodeContents(op1);
两个范围,通过selectNode和selectNodeContents方法来选区,有什么不同呢?oRange1选中的范围包括<p/>节点以及它的全部子节点,而oRange2只包含op1的子节点和文本节点(就是"<b>hello</b>world")。
(3)范围的特性:
<1>startContainer——范围是从哪个节点开始的,也就是第一个节点的父节点
<2>startOffset——在startContainer的偏移位置。
<3>endContainer——最后一个节点的父节点
<4>endOffset——在endContainer中范围结束的偏移位置
<5>commonAncestorContainer——startContainer和endContainer都处于哪个最小的节点
演示这些特性的例子:
<html>
<head>
<title>DOM Range Example</title>
<script type="text/javascript">
function useRanges() {
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById("p1");
oRange1.selectNode(oP1);
oRange2.selectNodeContents(oP1);
document.getElementById("txtStartContainer1").value = oRange1.startContainer.tagName;
document.getElementById("txtStartOffset1").value = oRange1.startOffset;
document.getElementById("txtEndContainer1").value = oRange1.endContainer.tagName;
document.getElementById("txtEndOffset1").value = oRange1.endOffset;
document.getElementById("txtCommonAncestor1").value = oRange1.commonAncestorContainer.tagName;
document.getElementById("txtStartContainer2").value = oRange2.startContainer.tagName;
document.getElementById("txtStartOffset2").value = oRange2.startOffset;
document.getElementById("txtEndContainer2").value = oRange2.endContainer.tagName;
document.getElementById("txtEndOffset2").value = oRange2.endOffset;
document.getElementById("txtCommonAncestor2").value = oRange2.commonAncestorContainer.tagName;
}
</script>
</head>
<body><p id="p1"><b>Hello</b> World</p>
<input type="button" value="Use Ranges" onclick="useRanges()" />
<table border="0">
<tr>
<td>
<fieldset>
<legend>oRange1</legend>
Start Container: <input type="text" id="txtStartContainer1" /><br />
Start Offset: <input type="text" id="txtStartOffset1" /><br />
End Container: <input type="text" id="txtEndContainer1" /><br />
End Offset: <input type="text" id="txtEndOffset1" /><br />
Common Ancestor: <input type="text" id="txtCommonAncestor1" /><br />
</fieldset>
</td>
<td>
<fieldset>
<legend>oRange2</legend>
Start Container: <input type="text" id="txtStartContainer2" /><br />
Start Offset: <input type="text" id="txtStartOffset2" /><br />
End Container: <input type="text" id="txtEndContainer2" /><br />
End Offset: <input type="text" id="txtEndOffset2" /><br />
Common Ancestor: <input type="text" id="txtCommonAncestor2" /><br />
</fieldset>
</td>
</tr>
</table>
<p><strong>Note:</strong> This example uses DOM ranges and will only work in browsers that support DOM ranges. This example will fail in Internet Explorer.</p>
</body>
</html>
Tags:javascript DOM 技术
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接