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

编程入门 行业动态 更新时间:2024-10-26 03:36:56
本文介绍了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 = 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,如何重新创建选择/范围?

本文发布于:2023-11-04 01:15:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556555.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!