Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

is there no way to create a reversed (i.e. right-to-left) selection from JavaScript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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-selection

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...