有没有办法从 JavaScript 创建一个反向(即从右到左)选择?

2022-01-24 00:00:00 selection range javascript

我正在尝试在文本中创建从右到左的选择,但似乎 DOM Range API 不允许我这样做.(我在规范中没有看到任何关于此的内容 - 并不是我仔细阅读了它 - 但所有实现似乎都同意不支持它.)

I'm trying to create a selection that goes from right to left in the text, but it seems the DOM Range API doesn't let me do that. (I don't see anything about this in the spec - not that I read it closely - but all implementations seem to agree on not supporting it.)

例如,给定一个非常小的文档:

For example, given a very minimal document:

data:text/html,<div> this is a test </div>

我可以使用这个脚本来启用编辑并创建一个正常的选择(例如从一个小书签,但为了清晰起见添加了换行):

I can use this script to enable editing and create a normal selection (for example from a bookmarklet, but line wrapping added for clarity):

javascript:document.designMode='on';
var r=document.createRange(),d=document.getElementsByTagName('div')[0]; 
r.setStart(d.firstChild, 3); 
r.setEnd(d.firstChild, 7); 
window.getSelection().addRange(r); void(0);

但是,如果我交换 3 和 7,则不会创建任何选择.

However, if I swap 3 and 7 no selection is created.

有人知道怎么做吗?

推荐答案

在所有主流浏览器的最新版本中都可以通过 extend() 方法的 Selection 对象.这是一个从 Range 创建向后选择的函数:

It's possible in recent versions of all major browsers except IE via the extend() method of the Selection object. Here's a function that creates a backwards selection from a Range:

function selectRangeBackwards(range) {
    var sel = window.getSelection();
    var endRange = range.cloneRange();
    endRange.collapse(false);
    sel.removeAllRanges();
    sel.addRange(endRange);
    sel.extend(range.startContainer, range.startOffset);
}

这在任何版本的 IE 中都是不可能的(直到并包括版本 11).虽然 IE 9 和更高版本确实实现了 DOM Level 2 Range 和 HTML5 Text Selection(现在迁移到 WHATWG Range 规范),他们实施时的规范版本 不包括 extend(),因此 IE 9 不支持它(另见 这个错误 用于进一步讨论向后选择).

This is not possible in any version of IE (up to and including version 11). While IE 9 and later does implement DOM Level 2 Range and HTML5 Text Selection (now migrated to the WHATWG Range spec), the version of the spec at the time they implemented it did not include extend(), so IE 9 does not support it (see also this bug for further discussion of backwards selections).

这是在 IE 错误跟踪器中实现 extend() 的请求:https://connect.microsoft.com/IE/feedback/details/737106/implement-missing-extend-method-of-selection

Here is the request to implement extend() in the IE bug tracker: https://connect.microsoft.com/IE/feedback/details/737106/implement-missing-extend-method-of-selection

在早期版本的 IE 中,选择 API 完全不同,也不支持以编程方式创建向后选择.

In earlier versions of IE, the selection API is completely different and does not have any support for programmatically creating backwards selections either.

相关文章