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

♀尐吖头ヾ 提交于 2019-11-28 04:30:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4801464/is-there-no-way-to-create-a-reversed-i-e-right-to-left-selection-from-javascr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!