如何使用哈希标记(“名称”)去到页面上,但在顶部固定的元素? [英] How use hash tag ("a name") to go to spot on page but account for a fixed element at top?
本文介绍了如何使用哈希标记(“名称”)去到页面上,但在顶部固定的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在网站上,顶部有一个菜单栏, position:fixed
, height:4em;
。当我点击一个散列链接< a href =#someName>转到< / a>
,它移动页面将 < a name =someName>< / a>
在窗口顶部,这意味着它在顶部栏下面,并部分隐藏。如何解释这个问题?
On the site, there is a menu bar at the top which is position: fixed
and is height: 4em;
. When I click a hash link <a href="#someName">go to</a>
, it moves the page to place the <a name="someName"></a>
at the top of the window, which means it is underneath the top bar, and partially hidden. How do I account for this?
http:// jsfiddle。 net / x3gr8s8z /
HTML:
<div class="topbar"></div>
<br /><br /><br /><br /><br />
<a href="#link">click me</a>
<a name="link"></a>
Going to here
CSS:
.topbar
{
position: fixed;
width: 100%;
height: 4em;
background-color: #cccccc;
}
推荐答案
并将窗口向下滚动固定元素的高度。
You could trap the hashchange event and scroll the window down by the height of the fixed element.
window.addEventListener('hashchange', function() {
window.scrollBy(0, -40);
});
而不是40,您可以使用
Instead of 40, you could use
document.querySelector('.topbar').getClientBoundingRect().height
这篇关于如何使用哈希标记(“名称”)去到页面上,但在顶部固定的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文