有没有办法从JavaScript创建反向(即从右到左)选择? [英] is there no way to create a reversed (i.e. right-to-left) selection from JavaScript?

查看:135
本文介绍了有没有办法从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.

有没有人知道这样做的方法?

Does anyone know a way to do this?

推荐答案

这是可以通过 extend()在除IE之外的所有主流浏览器的最新版本中实现选择对象的 方法。这是一个从范围创建向后选择的函数:

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 spec ),实施时的规范版本不包括 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-choice-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.

这篇关于有没有办法从JavaScript创建反向(即从右到左)选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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