我使用這個jQuery腳本做平滑滾動平滑滾動(上找到CSS-Tricks.com):jQuery的頁面加載
/** Smooth Scrolling Functionality **/
jQuery(document).ready(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');
var urlHash = '#' + window.location.href.split("#")[1];
$('a[href*=#]').each(function() {
$(this).click(function(event) {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'')) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.offset().top;
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target;
});
}
}
});
});
// use the first element that is "scrollable"
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 [];
}
});
/** END SMOOTH SCROLLING FUNCTIONALITY **/
它的工作太棒了,除了一兩件事,我希望它在有人直接訪問網址的情況下工作http://domain.com/page.html#anchor
它平滑地從頁面加載的頂部滾動到該錨點,現在它立即進入頁面錨點,除非它們已經點擊錨點。我希望這是有道理的。
,在我的問題的工作原理類似功能,但如果他們直接找到它並沒有解決問題到域名錨點(http://domain.com/page.html#anchor),它會立即轉到錨點,如果他們輸入到網址,而不是平滑滾動到它。 – Talon 2013-05-14 04:16:36
您可以使用動畫的 – PSR 2013-05-14 04:18:04
@Talon我更新我的代碼現在檢查一次。它正在按照你現在的要求工作 – PSR 2013-05-14 04:19:27