javascript 滚动到 div - jquery - 特定位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8082364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scroll to div - jquery - specific position
提问by user947462
I am trying this code:
我正在尝试这个代码:
function goToByScroll(id){
id = id.replace("link", "");
$('html,body').animate({
scrollTop: $("#"+id).offset().top},
'slow');
}
$("#sidebar > ul > li > a").click(function(e) {
e.preventDefault();
goToByScroll($(this).attr("id"));
});
The problem is that when i click in a specific element of list, the scroll go up to the top of the window. But in my case i have a fixed div in the top, so the content is hidden by this div. Well, I want stops the scroll before the div.
问题是,当我单击列表的特定元素时,滚动条会上升到窗口顶部。但在我的情况下,我在顶部有一个固定的 div,所以内容被这个 div 隐藏了。好吧,我想在 div 之前停止滚动。
any idea?
任何的想法?
回答by Kato
You need to give the top bar an id (e.g. id="header") and then subtract that from the scrollTop attribute:
您需要给顶部栏一个 id(例如 id="header"),然后从 scrollTop 属性中减去它:
$('html,body').animate({
scrollTop: ($("#"+id).offset().top-$('#header').outerHeight(true))+'px'},
'slow');
回答by David Horák
function goToByScroll(id){
id = id.replace("link", "");
$('html,body').animate({
scrollTop: ($("#"+id).offset().top - $("#YOUR_FIXED_DIV").height() ) },
'slow');
}
$("#sidebar > ul > li > a").click(function(e) {
e.preventDefault();
goToByScroll($(this).attr("id"));
});