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

how do I create a DOMSelection object from a specific node?

本文关键字:创建 DOMSelection 对象 节点      更新时间:2023-09-26

我的javascript不是那么好,所以我只能希望这是有意义的。 我想创建一个 DOMSelection 对象,就像从中返回的对象一样

window.getSelection()

因此,假设我有这样的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"

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

例:

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

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