How to position horizontal scroll bar at center of DIV

前端 未结 6 823
温柔的废话
温柔的废话 2020-12-18 01:51

I was trying to position horizontal scroll bar at the center of that div. I tired with window.scrollTo() but this works for page scroll and not for div scroll.



        
6条回答
  •  清歌不尽
    2020-12-18 02:23

    Might be usefull with some comments for better understanding, my approach:

    function scrollMeTo($Parent, $Child) {
    
        let parentHalf = $Parent.width() / 2; // half of parent width
        let childHalf = $Child.width() / 2; //half of child width
        let childPos = $Child.position().left; // X pos of child (relative to screen)
        //We increase X with the center of the child (childHalf) - scrolling here we see the right half of the child;
        //We decrease X with the parentHalf to obtain perfect center;
        let scroll = childPos + childHalf - parentHalf; //how much we need to scroll to the element
        //We now add the needed scroll to the current scroll.
        let nextScroll = $Parent.scrollLeft() + scroll;
        $Parent.scrollLeft(nextScroll);
    }
    

    Or use as one linear:

    function scrollMeTo($Parent,$Child){
           $Parent.scrollLeft($Parent.scrollLeft() + $Child.position().left + $Child.width() / 2 - $Parent.width() / 2);
    }
    

提交回复
热议问题