简体   繁体   English

Javascript,如何重新创建选择/范围?

[英]Javascript, how to recreate a selection / range?

In javascript: I need to grab a webpage selection, and then recreate the exact selection later. 在javascript中:我需要获取一个网页选择,然后稍后重新创建确切的选择。

I do this as below. 我这样做如下。 This works when the original selected is created forwards, but not when the original selection is made by moving the mouse backwards/up. 当向前创建原始所选内容时,此功能有效,但通过向后/向上移动鼠标进行原始选择时,此功能无效。 It does not throw an error, but nothing is selected. 它不会引发错误,但不会选择任何内容。 In this case, I need to switch the parameters for setStart() and setEnd(). 在这种情况下,我需要切换setStart()和setEnd()的参数。

How do I know that I need to do this? 我怎么知道我需要这样做? That the original selection was backwards or that one node comes after/before the other? 原来的选择是向后的,还是一个节点在另一个节点之后/之前?

EDIT: I'd like to use plain js, no extra libraries 编辑:我想使用纯js,没有额外的库

EDIT 2: I do not need this to work in old IE. 编辑2:我不需要此在旧的IE中工作。 IE9+ is fine. IE9 +很好。

// **** user makes selection

// **** get selection and range ****

var selection = window.getSelection(); 

var startNode = selection.anchorNode;
var endNode = selection.focusNode;

var startOffset = selection.anchorOffset;
var endOffset = selection.focusOffset;

// **** do stuff where selection is lost *****

// **** recreate selection as it was ****

var range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);

selection.removeAllRanges(); 
selection.addRange(range);  // works except when original selection was backwards

Using rangy.js you can save and restore selections easily 使用rangy.js,您可以轻松保存和还原选择

Live Demo 现场演示

var savedSel = rangy.saveSelection();

//Selection is lost

rangy.restoreSelection(savedSel);

source 资源

It looks like I need: 看来我需要:

x = startNode.compareDocumentPosition(endNode);

if (x == 4 || (x==0 && startOffset < endOffset)){
    range.setStart(startNode, startOffset);
    range.setEnd(endNode, endOffset);
}else{
     range.setStart(endNode, endOffset);
     range.setEnd(startNode, startOffset);
}

I don't think this works in older browsers, but it's fine for me. 我认为这不适用于较旧的浏览器,但对我来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM