有没有办法从 JavaScript 创建反向(即从右到左)选择?
我试图创建一个在文本中从右到左的选择,但 DOM Range API 似乎不允许我这样做。 (我在规范中没有看到任何有关此内容的内容 - 并不是我仔细阅读了它 - 但所有实现似乎都同意不支持它。)
例如,给定一个非常小的文档:
data:text/html,<div> this is a test </div>
我可以使用此脚本来启用编辑和创建普通选择(例如,从书签中,但为了清晰起见添加了换行):
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,则不会创建选择。
有谁知道如何做到这一点?
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);
However, if I swap 3 and 7 no selection is created.
Does anyone know a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在除 IE 之外的所有主要浏览器的最新版本中,都可以通过
extend()Selection
对象的 code> 方法。下面是一个从范围创建向后选择的函数:这在任何版本的 IE(直至并包括版本 11)中都是不可能的。虽然 IE 9 及更高版本确实实现了 DOM Level 2 Range 和 HTML5 Text Selection(现已迁移到 WHATWG Range 规范),实施时的规范版本 没有包含
extend()
,因此 IE 9 不支持它(另请参阅此错误以进一步讨论向后选择)。以下是在 IE bug 跟踪器中实现
extend()
的请求:https://connect.microsoft.com/IE/feedback/details/737106/implement-missing-extend-method-of-selection在早期版本中IE 的选择 API 完全不同,也不支持以编程方式创建向后选择。
It's possible in recent versions of all major browsers except IE via the
extend()
method of theSelection
object. Here's a function that creates a backwards selection from a Range: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).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-selectionIn earlier versions of IE, the selection API is completely different and does not have any support for programmatically creating backwards selections either.