简体   繁体   中英

scroll iframe to selected text

I am Using rangy to select a text in an IFrame selection is working but some times i need to scroll IFrame to view this selection. it is possible automatically scroll IFrame to the selected text?

You could use the scrollIntoView() method of the element containing the selection's anchor node, but that may scroll the main document as well as the iframe, and may also be inexact if the selection starts several lines into a text node, for example.

var sel = rangy.getSelection();
var anchorNode = sel.anchorNode;
if (anchorNode) {
    if (anchorNode.nodeType != 1) {
        anchorNode = anchorNode.parentNode;
    }
    anchorNode.scrollIntoView();
}

A better bet may be to use the selection range's bounding rectangle, available via the range's getBoundingClientRect() method in most modern browsers, and scroll the iframe's document manually. However, this is not universally supported and is relative to the viewport rather than the document. Here's a related question and answer:

https://stackoverflow.com/a/6847328/96100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM