Javascript scrollIntoView() middle alignment?

后端 未结 10 1409
刺人心
刺人心 2020-12-13 03:41

Javascript .scrollIntoView(boolean) provide only two alignment option.

  1. top
  2. bottom

What if I want to scroll the view such t

10条回答
  •  余生分开走
    2020-12-13 03:59

    It is possible to use getBoundingClientRect() to get all the information you need to achieve this. For example, you could do something like this:

    const element = document.getElementById('middle');
    const elementRect = element.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (window.innerHeight / 2);
    window.scrollTo(0, middle);
    

    Demo: http://jsfiddle.net/cxe73c22/

    This solution is more efficient than walking up parent chain, as in the accepted answer, and doesn't involve polluting the global scope by extending prototype (generally considered bad practice in javascript).

    The getBoundingClientRect() method is supported in all modern browser.

提交回复
热议问题