HTML5 编辑 API 之 Range 对象(一)
一、基本概念
https://developer.mozilla.org/en-US/docs/Web/API/Range
https://developer.mozilla.org/en-US/docs/Web/API/Selection
1.The Range
interface represents a fragment of a document that can contain nodes and parts of text nodes.
A range can be created using the createRange()
method of the Document
object. Range objects can also be retrieved by using the getRangeAt()
method of the Selection
object or thecaretRangeAtPoint()
method of the Document
object.
There also is the Range()
constructor available.
2.Range的selectionNode与selectionNodeContents方法
用法:range.selectNode(referenceNode);
var range = document.createRange();
var referenceNode = document.getElementsByTagName("div").item(0);
range.selectNode(referenceNode);
用法:range.selectNodeContents(referenceNode);
range = document.createRange();
referenceNode = document.getElementsByTagName("div")[0];
range.selectNodeContents(referenceNode);
3.A Selection object represents the range of text selected by the user or the current position of the caret. To obtain a Selection object for examination or modification, callwindow.getSelection().
Notes
String representation of a selection
Calling the Selection.toString() method returns the text contained in the selection, e.g.:
var selObj = window.getSelection();
window.alert(selObj);
Note that using a selection object as the argument to window.alert will call the object'stoString method.
Multiple ranges in a selection
A selection object represents the ranges that the user has selected. Typically, it holds only one range, accessed as follows:
var selObj = window.getSelection();
var range = selObj.getRangeAt(0);
selObj is a Selection object
range is a Range object
3.示例
(1)selection
(2)range
二、Range方法之setStartsetEnd等方法
1.setStart,setEnd
https://developer.mozilla.org/en-US/docs/Web/API/Range/setStart
https://developer.mozilla.org/en-US/docs/Web/API/Range/setEnd
2.setStartBefore,setEndAfter