JavaScript - 向下滚动到元素 [英] JavaScript - Scroll down to element

查看:53
本文介绍了JavaScript - 向下滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用带有标签和元素ID的网址滚动到一个元素:

  window.location.href = #ID

这将滚动,以便元素的顶部位于浏览器的顶部。我如何滚动到一个元素,以便它的垂直居中?

不,没有内置的方式,你会必须自己写:

pre $ function center_element_vertically(elt){
var rect = elt.getBoundingClientRect();
window.scrollTo(0,rect.top + window.pageYOffset -
(window.innerHeight - rect.height)/ 2);
}

另一种方式不用编写自己的代码:您可以滚动以便元素处于通过将 false 传递给 scrollIntoView ,或者只在元素不可见时通过调用 scrollIntoViewIfNeeded ,仅在Chrome AFAIK中可用。


You can scroll to an element using a url with a hashtag and the elements ID:

window.location.href = "#ID"

This will scrol so that the top of the element is at the top of the browser. How would I scroll to an element so that it's vertically centered?

解决方案

No, there's no built-in way, you'd have to write that yourself:

function center_element_vertically(elt) {
    var rect = elt.getBoundingClientRect();
    window.scrollTo(0, rect.top + window.pageYOffset - 
        (window.innerHeight - rect.height)/2);
}

Alternatives without writing your own code: you could scroll so that the element was at the bottom by passing false to scrollIntoView, or scroll only if the element is not already visible by calling scrollIntoViewIfNeeded, available only in Chrome AFAIK.

这篇关于JavaScript - 向下滚动到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆