Scroll to the center of viewport

后端 未结 4 1820
南笙
南笙 2021-01-31 12:18

I would like to center a div by clicking it. So if I\'m clicking a div I want it to scroll to the center of the browser viewport. I don\'t want to use

4条回答
  •  遥遥无期
    2021-01-31 12:33

    HTMLElement.prototype.scrollToCenter = function(){
        window.scrollBy(0, this.getBoundingClientRect().top - (window.innerHeight>>1));
    }
    

    Achieved with pure JavaScript for Scrolling to Center in the vertical direction. And it's similar in the horizontal direction. I don't take elements' height into consideration, because they maybe larger than the height of screen.

提交回复
热议问题