ScrollIntoView() causing the whole page to move

后端 未结 12 2045
庸人自扰
庸人自扰 2020-11-30 21:40

I am using ScrollIntoView() to scroll the highlighted item in a list into view. When I scroll downwards ScrollIntoView(false) works perfectly. But when I scroll upwards, Scr

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 22:01

    Using Brilliant's idea, here's a solution that only (vertically) scrolls if the element is NOT currently visible. The idea is to get the bounding box of the viewport and the element to be displayed in browser-window coordinate space. Check if it's visible and if not, scroll by the required distance so the element is shown at the top or bottom of the viewport.

        function ensure_visible(element_id)
        {
            // adjust these two to match your HTML hierarchy
            var element_to_show  = document.getElementById(element_id);
            var scrolling_parent = element_to_show.parentElement;
    
            var top = parseInt(scrolling_parent.getBoundingClientRect().top);
            var bot = parseInt(scrolling_parent.getBoundingClientRect().bottom);
    
            var now_top = parseInt(element_to_show.getBoundingClientRect().top);
            var now_bot = parseInt(element_to_show.getBoundingClientRect().bottom);
    
            // console.log("Element: "+now_top+";"+(now_bot)+" Viewport:"+top+";"+(bot) );
    
            var scroll_by = 0;
            if(now_top < top)
                scroll_by = -(top - now_top);
            else if(now_bot > bot)
                scroll_by = now_bot - bot;
            if(scroll_by != 0)
            {
                scrolling_parent.scrollTop += scroll_by; // tr.offsetTop;
            }
        }
    

提交回复
热议问题