javascript 滚动到锚点上方 100 像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18274394/
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 100px above the anchor
提问by Wiseguy
I'm using the the JavaScript code below to create a scroll effect from my nav to the anchor.
我正在使用下面的 JavaScript 代码来创建从我的导航到锚点的滚动效果。
The problem I am having is I want the scrolling to stop 100px above the anchor.
我遇到的问题是我希望滚动停止在锚点上方 100 像素处。
What would I need to change in this code to achieve this result?
我需要在此代码中更改哪些内容才能实现此结果?
$(document).ready(function() {
$('a[href^="#"]').click(function() {
var target = $(this.hash);
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top }, 1000);
return false;
});
});
Thank you
谢谢
回答by Damiaan Dufaux
Subtract 100 pixels from target.offset().top. like so:
从 target.offset().top 中减去 100 像素。像这样:
$(document).ready(function() {
$('a[href^="#"]').click(function() {
var target = $(this.hash);
if (target.length == 0) target = $('a[name="' + this.hash.substr(1) + '"]');
if (target.length == 0) target = $('html');
$('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
return false;
});
});