我在下面这样做:我需要抓住一个网页选择,然后再重新确定选择。当原始选择被创建为前进时,这可以工作,但是当通过向后/向上移动鼠标进行原始选择时,此功能不起作用。它不会出错,但没有选择。在这种情况下,我需要切换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 = startNodepareDocumentPosition(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 = startNodepareDocumentPosition(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,如何重新创建选择/范围?
发布评论