我已在my site上實施了CSS Tricks Smooth Page Scroll,它的工作非常好。但是,因爲我在頁面頂部有一個固定的導航欄,所以當頁面滾動到適當的錨點div時,div的頂部會消失在導航欄後面。我怎樣才能抵消滾動(約70px),以便顯示整個div?我試過這樣做:如何爲平滑滾動設置偏移量
var targetOffset = $target.offset().top - 70;
但是這並不奏效。該頁面會滾動到合適的位置,但會立即跳回,以便隱藏div的頂部。我錯過了什麼?以下是代碼全部:
$(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
// Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
$('a[href*=#]').each(function() {
// Ensure it's a same-page link
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'')) {
// Ensure target exists
var $target = $(this.hash), target = this.hash;
if (target) {
// Find location of target
var targetOffset = $target.offset().top - 70;
$(this).click(function(event) {
// Prevent jump-down
event.preventDefault();
// Animate to target
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// Set hash in URL after animation successful
location.hash = target;
});
});
}
}
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
});
在此先感謝您的幫助。
我發現這個[鏈接](http://css-tricks.com/forums/discussion/17304/adding-margin-top-to-scroll-js/p1),幫助我理解的原因爲什麼它跳躍是因爲它在動畫之後重置了URL。所以,現在我有一個新的問題,有什麼方法可以重置網址並擺脫跳躍?我希望URL能夠反映用戶在頁面上的位置。 – mcography