本文转载自:http://blog.sina.com.cn/s/blog_50122c300100fbqs.html
前言:由于最近在做Web html 编辑器,会用range方面知识,在查找资料的时候,发到本文,觉得对自己有帮助,特此转载。
Ranges
To allow an even greater measure of control over a page, you canuse something called a range. A range can be used to select asection of a document regardless of node boundaries (note that theselection occurs behind the scenes and
cannot be seen by theuser).
Ranges are helpful when regular DOM manipulation isn’t specificenough to change a document. And as usual, there are two differentimplementations of ranges: one from the DOM and one from InternetExplorer.
Ranges
Simple selection in DOM ranges
The simplest way to select a part of the document using a range isto use either selectNode() or selectNodeContents(). These methodseach accept one argument, a DOM node, and fill a range withinformation from that node.
The selectNode() method selects the entire node, including itschildren, whereas
selectNodeContents() selects all of the node’s children.
DOM ranges中的简单选中:
Whenever you create a range, a number of properties are assigned toit:
1,startContainer — The node within which the range starts (theparent of the first node in the selection)
2,startOffset — The offset within the startContainer where therange starts. If
startContainer is a text node, comment node, or CData node, thestartOffset is the number of characters skipped before the rangestarts; otherwise, the offset is the index of the first child nodein the range.
3,endContainer — The node within which the range ends (the parentof the last node in the selection)
4,endOffset — The offset within the endContainer where the rangeends (follows the same rules as startOffset)
5,commonAncestorContainer — The first node within which bothstartContainer and
endContainer exist
These properties are all read-only and are designed to give youadditional information about the range.
1,startContainer-range开始的节点(选中区的第一个节点的父节点)。
2,startOffset-在range开始的startContainer里面的offset。假如startContainer是一个文本节点,注释节点或者CData节点,startOffset是range开始前跳过的字母的数量;否则offset是range第一个子节点的索引。
3,endContainer-range结束的节点(选中区的最后节点的父节点)
4,endOffset-在range结束的endContainer里面的offset。(遵循startOffset规则)
5,commonAncestorContainer-startContainer和endContainer都存在其中的第一个节点。
When you use selectNode(), the startContainer, endContainer, andcommonAncestorContainer are all equal to the parent node of thenode that was passed in; startOffset is equal to the index of thegiven node within the parent’s childNodes collection, whereasendOffset
is equal to the startOffset plus one (because only onenode is selected).
When you use selectNodeContents(), startContainer, endContainer,and commonAncestor Container are equal to the node that was passedin; startOffset is equal to 0; endOffset is equal to the number ofchild nodes (node.childNodes.length).