首页 > 解决方案 > scrollintoview() 被粘性导航栏阻止

问题描述

由于某些未知的原因,我的导航栏阻止了 div 内容。

下面是我的示例代码。如何修复它,以便在div单击按钮时不会被粘性导航栏阻止?

<div style="height:90px; border: 1px solid red; background-color: grey; position: fixed; width: 100%;">Navbar</div>

<div id="A">
This text will blocked by sticky navbar
<br/>A<br/><br/><br/><br/><br/>---
</div>

<div id="B">
This text will blocked by sticky navbar
<br/>B<br/><br/><br/><br/><br/>---
</div>

<br/><br/><br/><br/><br/><br/><br/>

<button onClick="document.getElementById('A').scrollIntoView();">A</button>
<button onClick="document.getElementById('B').scrollIntoView();">B</button>

标签: javascripthtml

解决方案


您必须从顶部留下一些像素,以便内容看起来从导航栏的底部开始。在这种情况下padding-bottom工作。

function scrollToView(id){
  var top = document.getElementById(id).offsetTop-document.getElementById("nav").offsetHeight-10;
  //show 10 pixels down the border
  window.scrollTo(0, top);
}
<div style="height:90px; border: 1px solid red; background-color: grey; position: fixed; width: 100%;" id="nav">Navbar</div>

<div id="A" style="padding-top: 100px">
This text will blocked by sticky navbar
<br/>A<br/><br/><br/><br/><br/>---
</div>

<div id="B">
This text will blocked by sticky navbar
<br/>B<br/><br/><br/><br/><br/>---
</div>

<br/><br/><br/><br/><br/><br/><br/>
<div id="C">
This text will blocked by sticky navbar
<br/>C<br/><br/><br/><br/><br/>---
</div>

<button onClick="scrollToView('A')">A</button>
<button onClick="scrollToView('B')">B</button>


推荐阅读