Bas*_*ang 5 html javascript css jquery
我的页面有一个固定的顶部导航栏,页面上有几个id元素.如果我按下这些id元素中的一个链接,它会将此id滚动到顶部,但它隐藏在顶部导航栏下方.在野外,页面很长,并且具有不同的"跳跃点".
我有一个简化的小提琴来显示以下html 的问题
<div id="fixedbar">This is the fixed top bar</div>
<div id="toplinks"><a href="#first">First</a> <a href="#second">Second</a></div>
<p id="first"><strong>First</strong>
Lorem ipsum dolor sit amet[...]
</p>
<p id="second"><strong>Second</strong>
Duis autem vel eum iriure dolor[...]
</p>
<div id="bottomlinks"><a href="#first">First</a> <a href="#second">Second</a></div>
Run Code Online (Sandbox Code Playgroud)
这个css
body{padding:0;margin:0}
#toplinks{padding-top:2em}
#fixedbar{
position:fixed;
background-color:#ccc;
height:2em;
width:100%
}
Run Code Online (Sandbox Code Playgroud)
我想要点击一个链接滚动到右边的元素,但补充固定的导航栏.一个可能的解决方案最多只包括css,但可以包括javascript或jquery(1.9是生产用).
感谢您的任何帮助!
这是JavaScript解决此问题的方法.将单击事件绑定到<a>顶部链接和底部链接,单击事件查找目标<p>偏移量并使用javascript滚动到它.
$("#toplinks, #bottomlinks").on('click','a', function(event){
event.preventDefault();
var o = $( $(this).attr("href") ).offset();
var sT = o.top - $("#fixedbar").outerHeight(true); // get the fixedbar height
// compute the correct offset and scroll to it.
window.scrollTo(0,sT);
});
Run Code Online (Sandbox Code Playgroud)
小提琴:http://jsfiddle.net/AnmJY/1/