Scrolling to an item in a div

I have an absolutely positioned div that acts like a modal window in the center of the page. The modal window scrolls vertically using the scroll bar on the right side. The page itself also scrolls vertically using the scroll bar on the right. I would like to be able to click on the link and scroll the modal window to the related item.

I can pretty much achieve this using target.scrollIntoView (); but the whole page scrolls along with the modal window - I would like the page to not move and only have to scroll the modal window. If I use scrollIntoView (false), the page itself does not scroll, while the modal window does, but the target element is at the bottom of the window, while I would like it to be at the top.

Is there a way that I can manually shift the position of a target in a div? that is, if I use scrollIntoView (false), the target is displayed at the bottom of the div - if I could then shift it to the height of the viewport, could I move it to the beginning.?

Note. I can not use jQuery and the like. for this.

Thanks in advance for your help.

+3
source share
2 answers

Here is a live demo that I think does what you are looking for: http://jsfiddle.net/QN3mK/

Code for this: (basically check the function scrollFunc())

function scrollFunc() {
    var est = document.getElementById('est');
    var docPos = f_scrollTop();
    est.scrollIntoView();
    window.scrollTo(0,docPos);
}

function f_scrollTop() {
    return f_filterResults (
        window.pageYOffset ? window.pageYOffset : 0,
        document.documentElement ? document.documentElement.scrollTop : 0,
        document.body ? document.body.scrollTop : 0
    );
}

function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

The second two functions are just the cross-browser way I found to get the current scroll position of the page. So, what is it like to find an element (presumably in a scrollable div), get the current scroll position of the page, scroll the element in the form (which puts it at the top of the scrollable div), and then reset the page position back to where it was. This is probably not an ideal solution, but it will do its job.

+5
source

You can experiment with assigning integer values ​​to the scrollTop property.

0

Source: https://habr.com/ru/post/1765180/


All Articles