103

Javascript.scrollIntoView(boolean)は 2 つの配置オプションのみを提供します。

そのようにビューをスクロールしたい場合はどうなりますか。ページの途中に特定の要素を配置したいですか?

4

10 に答える 10

136

これを試して :

 document.getElementById('myID').scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'center'
        });

詳細とオプションについては、こちらを参照してください: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

于 2018-05-21T17:31:49.863 に答える
53

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 );
于 2012-01-19T09:53:17.060 に答える
1

scrollIntoViewOptionsすべてのブラウザーですべてのオプションをサポートするには、 seamless-scroll-polyfill ( https://www.npmjs.com/package/seamless-scroll-polyfill )を使用することをお勧めします。

私のために働いた。

ここに説明付きのリンクがあります https://github.com/Financial-Times/polyfill-library/issues/657

于 2020-10-09T10:40:58.237 に答える