如何从特定节点创建DOMSelection对象?

时间:2012-04-28 21:24:34

标签: javascript webkit dom-selection

我的javascript不是很好,所以我只希望这是有道理的。我想创建一个DOMSelection对象,就像从

返回的对象一样
window.getSelection()

来自节点的onclick。所以假设我有这样的jQuery监听器设置:

$("#target").click(function() {
    var sel = createSelectionFromNode(this);
});

我只希望范围从节点的开头到节点的结尾。是否有捷径可寻?我特意寻找WebKit兼容的解决方案,可以忽略IE。谢谢你的帮助。

示例:http://jsfiddle.net/8j4Bf/

在示例中,单击文本应返回DOMSelection对象,如:

DOMSelection
anchorNode: Text
    attributes: null
    baseURI: "http://jsfiddle.net/8j4Bf/"
    childNodes: NodeList[0]
    data: "HTML"
    firstChild: null
    lastChild: null
    length: 4
    localName: null
    namespaceURI: null
    nextSibling: null
    nodeName: "#text"
    nodeType: 3
    nodeValue: "HTML"
    ownerDocument: HTMLDocument
    parentElement: HTMLSpanElement
    parentNode: HTMLSpanElement
    prefix: null
    previousSibling: null
    textContent: "HTML"
    wholeText: "HTML"
    __proto__: Text
anchorOffset: 0
baseNode: Text
baseOffset: 0
extentNode: Text
extentOffset: 0
focusNode: Text
    attributes: null
    baseURI: "http://jsfiddle.net/8j4Bf/"
    childNodes: NodeList[0]
    data: "HTML"
    firstChild: null
    lastChild: null
    length: 4
    localName: null
    namespaceURI: null
    nextSibling: null
    nodeName: "#text"
    nodeType: 3
    nodeValue: "HTML"
    ownerDocument: HTMLDocument
    parentElement: HTMLSpanElement
    parentNode: HTMLSpanElement
    prefix: null
    previousSibling: null
    textContent: "HTML"
    wholeText: "HTML"
    __proto__: Text
focusOffset: 0
isCollapsed: true
rangeCount: 1
type: "Caret"

1 个答案:

答案 0 :(得分:0)

你在寻找像document.getSelection()这样的东西吗?我有点困惑,所以我提前道歉。

示例:

http://jsfiddle.net/8j4Bf/1/

https://developer.mozilla.org/en/DOM/document.getSelection