Javascript scrollIntoView() middle alignment?

后端 未结 10 1348
刺人心
刺人心 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 04:03

    You can do it in two steps :

    myElement.scrollIntoView(true);
    var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    window.scrollBy(0, -viewportH/2); // Adjust scrolling with a negative value here
    

    You can add the height of the element if you want to center it globaly, and not center its top :

    myElement.scrollIntoView(true);
    var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    window.scrollBy(0, (myElement.getBoundingClientRect().height-viewportH)/2);
    

提交回复
热议问题