Javascript,如何重新创建选择/范围? [英] Javascript, how to recreate a selection / range?

查看:207
本文介绍了Javascript,如何重新创建选择/范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在下面这样做:我需要抓住一个网页选择,然后再重新确定选择。当原始选择被创建为前进时,这可以工作,但是当通过向后/向上移动鼠标进行原始选择时,此功能不起作用。它不会出错,但没有选择。在这种情况下,我需要切换setStart()和setEnd()的参数。



我如何知道我需要这样做?原来的选择是向后的,还是一个节点在另一个节点之后/之前?



编辑:我想使用普通的js,没有额外的库



编辑2:我不需要这个工作在旧的IE。 IE9 +很好。

  // ****用户选择

// *** *获取选择和范围****

var selection = window.getSelection();

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

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

// ****做选择丢失的东西*****

// ****重新选择,因为它是****

var range = document.createRange();

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

selection.removeAllRanges();
selection.addRange(range); //作品,除非原始选择是向后的


解决方案

像我需要的:

  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);
}

我不认为这在旧版浏览器中有效,但对我来说。


In javascript: I need to grab a webpage selection, and then recreate the exact selection later.

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().

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

EDIT 2: I do not need this to work in old IE. IE9+ is fine.

// **** 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

解决方案

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.

这篇关于Javascript,如何重新创建选择/范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆