DHR*_*SAL 62 javascript javascript-events js-scrollintoview
Javascript .scrollIntoView(boolean)只提供两个对齐选项.
如果我想滚动视图怎么办?我想把特定元素带到页面中间的某个地方?
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
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)
Gre*_* R. 10
document.getElementById("id").scrollIntoView({block: "center"});
Run Code Online (Sandbox Code Playgroud)
小智 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
您可以分两步完成:
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)
| 归档时间: |
|
| 查看次数: |
43939 次 |
| 最近记录: |