css – Div锚点滚动得太远了

我在我的网站顶部使用静态条,大约20px高。当我点击一个锚点链接时(对于那些不知道的人来说,维基百科上的导航就像那样。点击一个标题,然后浏览器就可以了。)文本的一部分消失在顶部栏后面。

有没有办法阻止这种情况发生?我不能使用iFrame。我能想到的只是让它每次都回滚一下,但还有另一种方式吗?一些CSS设置来操纵身体或什么?

解决方法

要使用CSS修复此问题,您可以向要跳转到的元素添加填充:

Example

或者,您可以添加边框:

div{ height: 650px; background:#ccc; 
     /*the magic happens here*/
     border-top:42px solid #fff;
}
ul{top: 0; width: 100%; height:20px; position: fixed; background: deeppink; margin:0;padding:10px; }
li{float:left;list-style:none;padding-left:10px}
div:first-of-type{ margin-top:0; }
<!-- content to be placed inside <body>…</body> -->
<ul>
	<li><a href="#s1">link 1</a>
	<li><a href="#s2">link 2</a>
	<li><a href="#s3">link 3</a>
	<li><a href="#s4">link 4</a>
</ul>
<div id="s1" class="first">1</div>
<div id="s2">2</div>
<div id="s3">3</div>
<div id="s4">4</div>

但是,这并不总是适用。

对于javascript解决方案,您可以使用附加到锚元素的单击事件来滚动调整后的像素数量,如下所示:

document.querySelector("a").addEventListener("click",function(e){
    // dynamically determining the height of your navbar
    let navbar = document.querySelector("nav");
    let navbarheight = parseInt(window.getComputedStyle(navbar).height,10);
    // show 5 pixels of prevIoUs section just for illustration purposes 
    let scrollHeight = document.querySelector(e.target.hash).offsetTop - navbarheight - 5;
    /* scrolling to the element taking the height of the static bar into account*/
    window.scroll(0,scrollHeight);
    /*properly updating the window location*/
    window.location.hash = e.target.hash;
    /* do not execute default action*/
    e.preventDefault();
});
nav{
position:fixed;top:0;left:0;right:0;height:40px;text-align:center;background:#bada55;margin:0;
}
a{display:block;padding-top:40px;}
#section1{
height:800px;background:repeating-linear-gradient(45deg,#606dbc55,#606dbc55 10px,#46529855 10px,#46529855 20px);
}
#section2{
height:800px;background:repeating-linear-gradient(-45deg,#22222255,#22222255 10px,#66666655 10px,#66666655 20px);
}
<nav>static header</nav>
<a href="#section2">jump to section 2</a> 
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效