javascript - 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>
解决方案
您必须从顶部留下一些像素,以便内容看起来从导航栏的底部开始。在这种情况下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>
推荐阅读
- tags - 如何在 github 操作中获取上一个标签,然后将其与当前标签进行比较?
- python - 在 python 中使用 train_test_split 将数据拆分为训练和测试时缺少一行
- c# - 我应该怎么做才能从 Unity/C#/vs 代码连接和查询 Heroku PostgreSQL?
- oracle - oracle sum error 查询中的复数差异
- javascript - 用户对象在压缩图片保存之前被执行,我该如何更改?
- flask - 为什么我上传的图片没有显示在heroku上
- java - 将 JSON 映射到包含地图的自定义对象
- python - 如何修复本地文件的 pickle-data-was-truncated 错误?
- heroku - 如何设置在运行时生成的新页面的预呈现 HTML 与 Next.js 中的增量静态生成 (ISR) 一起存储到 AWS S3 的位置?
- javascript - 在反应中扩展/扩展并填充导航栏的搜索栏