Javascript scrollIntoView()中间对齐?

DHR*_*SAL 62 javascript javascript-events js-scrollintoview

Javascript .scrollIntoView(boolean)只提供两个对齐选项.

  1. 最佳
  2. 底部

如果我想滚动视图怎么办?我想把特定元素带到页面中间的某个地方?

Roh*_*ton 62

可以使用getBoundingClientRect()获取实现此目的所需的所有信息.例如,你可以这样做:

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);
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/cxe73c22/

这个解决方案比在父链上行走更有效,就像在接受的答案中一样,并且不涉及通过扩展原型来污染全局范围(通常被认为是javascript中的不良做法).

getBoundingClientRect()所有现代浏览器都支持该方法.


Sri*_*ri7 50

试试这个 :

 document.getElementById('myID').scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'center'
        });
Run Code Online (Sandbox Code Playgroud)

有关更多信息和选项,请参阅此处:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

  • 与polyfill结合使用,这是最好的答案.https://www.npmjs.com/package/smoothscroll-polyfill (7认同)
  • 只有 Chrome 和 Opera 完全支持块和内联,即使是 smoothscroll polyfill 也不支持。这是我们想要的解决方案,但遗憾的是不是有效的解决方案。 (5认同)
  • @Sri7 Safari、IE 和 Edge 不理解 `scrollIntoView` 的对象选项,可以为所欲为。即使是最新版本;我刚刚又测试了一遍。 (2认同)

Thi*_*iff 41

使用window.scrollTo()此.获取要移动到的元素的顶部,并减去窗口高度的一半.

演示: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 );
Run Code Online (Sandbox Code Playgroud)

  • 走整个父链有点低效 (3认同)

Gre*_* R. 10

document.getElementById("id").scrollIntoView({block: "center"});
Run Code Online (Sandbox Code Playgroud)

  • 我需要这个用于具有固定标题的垂直滚动表,这对我有用。 (2认同)

小智 9

如果其父元素具有 css,则滚动到元素的中间效果很好: overflow: scroll;

如果它是一个垂直列表,您可以使用document.getElementById("id").scrollIntoView({block: "center"});它,它会将您选择的元素滚动到父元素的垂直中间。

为 Gregory R. 和 Hakuna 的好答案干杯。

进一步阅读:

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow


fre*_*727 7

您可以分两步完成:

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
Run Code Online (Sandbox Code Playgroud)

如果要将其置于球体中心,并且不将其顶部居中,则可以添加元素的高度:

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

  • 这是2018年的最佳答案。首先使用常规的“ scrollIntoView”,因为Firefox 36至58中的“ ​​center”选项已损坏,并且IE不支持该选项,请参阅https://developer.mozilla.org/en -US / docs / Web / API / Element / scrollIntoView#Browser_compatibility。然后您可以通过计算视口的一半将滚动条居中,然后将滚动条移到那里。 (2认同)