简体   繁体   English

单击锚点链接时垂直居中div

[英]Vertically center div when clicking on an anchor link

What I want to do is have an anchor link that links to a div lower on the page. 我想做的是有一个链接到页面下方div的锚链接。 Normally the way this works is it scrolls down to the anchor, positioning it at the top of the window. 通常,它的工作方式是向下滚动到锚点,将其定位在窗口的顶部。 Is there a way to get it to scroll down and center it instead? 有没有办法让它向下滚动并居中?

I've sort of worked around this by putting another div inside, giving it an absolute position of top: calc(-50vh + 200px);, and making this the anchor. 我已经通过在其中放置另一个div来解决此问题,并为其赋予了top的绝对位置:calc(-50vh + 200px);,并将其作为锚。

This works fine in Firefox and IE, but not in Chrome. 这在Firefox和IE中可以正常工作,但在Chrome中则不能。 I'm assuming this isn't the best way to do it anyway. 我以为这不是最好的方法。 I'm sure there's some way of accomplishing this with Javascript, but I haven't found any working examples. 我敢肯定有某种方法可以用Javascript完成,但是我还没有找到任何可行的例子。 Does anyone have a clue as to how this can be accomplished? 有没有人知道如何实现这一目标?

You could try: 您可以尝试:

window.scrollTo(x, y);

If you don't want to hardcode the value for y, you can use jQuery's .position() method to find the value for y. 如果您不想对y的值进行硬编码,则可以使用jQuery的.position()方法来查找y的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM