How To Select A Range in an Iframe With “Start” and “End” in Firefox like “selectionStart” from inputs element

為{幸葍}努か 提交于 2019-12-13 15:24:17

问题


for Internet Explorer, I have the current code to select a range in an iframe with desingMode setting to on:

    var Range = window.document.selection.createRange();
    var obj = { start: 3, end : 6}
    Range.collapse( true );
    Range.moveStart( 'character', obj.start );
    Range.moveEnd( 'character', obj.end - obj.start );
    Range.select();

Most useful if I want select only one piece of a string by only 2 parameters. Start and End ( for input elements exists the properties selectionStart and selectionEnd ).

When this code is executed, for example, on a string "Hello World", it highlight only the piece of string llo Wo, or something like that.
The problem is that Firefox Dom do not support the method moveStart or moveEnd, but only range.setStart and range.setEnd which request only a node and an offset as arguments.

So is possible to virtualizing the moveStart and the moveEnd methods in Firefox? Thanks.


回答1:


This works for me:

var iframeElement = ...; // the DOM element for the iframe;

var contentDoc = iframeElement.contentDocument;
var range = contentDoc.createRange();
range.setStart(contentDoc.body.firstChild, 3);
range.setEnd(contentDoc.body.firstChild, 6);
var selection = iframeElement.contentWindow.getSelection();
selection.removeAllRanges();
selection.addRange(range);

You need to call removeAllRanges() in Firefox or else you can end up with multiple selections.



来源:https://stackoverflow.com/questions/2385773/how-to-select-a-range-in-an-iframe-with-start-and-end-in-firefox-like-selec

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