Scroll to element only if not in view - jQuery

前端 未结 10 1222
醉酒成梦
醉酒成梦 2020-12-13 18:26

I know a variation on this has been asked several times; I\'ve been browsing SO for a while now but either I\'m doing something wrong or I haven\'t found what I need.

<
10条回答
  •  再見小時候
    2020-12-13 18:38

    JQuery is not required for this.

    This function just shows the specified element:

    function scrollIntoView(elm) {
        if(elm) {
            let bnd=elm.getBoundingClientRect();
            if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
            else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
            }
        return elm;
        }
    

    The following more capable function allows a container of the desired element to be scrolled into view, also providing the ability to easily ensure that the entire container is made visible so that half-occluded visuals are avoided.

    /**
      * Scroll the specified element into view, optionally first searching for a specific container and
      * first making that visible. This function does it's best to scroll the entire container into view
      * but ultimately ensures that as much of the element as fits in the viewport will be visible.
      *
      * #### Arguments:
      *
      *     elm (DOMElement)    The element to make visible.
      *     contag (string)     Optional name of a container tag. Ignored if blank/null/omitted.
      *     conprp (string)     Optional name of a container property to also match. Ignored if blank/null/omitted.
      *     conval (string)     Optional value of the container property. Ignored if `conprp` is not supplied; defaults to "" if omitted.
      */
    function scrollIntoView(elm,contag,conprp,conval) {
        if(elm) {
            if(contag || conprp) {
                let con;
                if(conval==null) { conval=""; }
                for(con=elm; con!=null && con.tagName!="BODY"; con=con.parentNode) {
                    if((!contag || contag==con.tagName) && (!conprp || con[conprp]==conval)) {
                        break;                                                                          // matched container tag and property
                        }
                    }
                if(con) { scrollIntoView(con); }
                }
    
            let bnd=elm.getBoundingClientRect();
    
            if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
            else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
            }
        return elm;
        }
    

    This makes it easy to, for example, show this when scrolling up:

    instead of this:

提交回复
热议问题