How To Select A Range in an Iframe With “Start” an

2019-07-17 18:04发布

问题:

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.