Javascript scrollIntoView() middle alignment?

后端 未结 10 1362
刺人心
刺人心 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:49

    Use window.scrollTo() for this. Get the top of the element you want to move to, and subtract one half the window height.

    Demo: http://jsfiddle.net/ThinkingStiff/MJ69d/

    Element.prototype.documentOffsetTop = function () {
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
    };
    
    var top = document.getElementById( 'middle' ).documentOffsetTop() - ( window.innerHeight / 2 );
    window.scrollTo( 0, top );
    

提交回复
热议问题