我需要平滑滚动偏移100px。到目前为止,我有这个:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
这让我的链接移动了!但是如何添加.offset()。top>这个100?如果有人可以提供帮助,我会遇到问题。
答案 0 :(得分:1)
ve1jdramas 你好。
看看 link here 。
在此示例中,他们使用 + 或 - 。
像这样......
scrollTop: target.offset().top -100
或
scrollTop: target.offset().top +100
试试这个,看看你是否可以让它为你工作 或者使用此完整代码。
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top -100
}, 1000);
return false;
}
}
});
});
答案 1 :(得分:1)
听起来你有一个固定的导航栏。假设你的锚是空的:
<a class="anchor" id="foo"></a>
只是偏移css中的锚点:
.anchor {
top: -100px;
position: relative;
display: block;
}
或者,您可以通过更新javascript:
来抵消scrollTopscrollTop: $($anchor.attr('href')).offset().top - 100