我正在使用这个 jQuery 脚本进行平滑滚动(在 CSS-Tricks.com 上找到):
/** 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 **/
它工作得很好,除了一件事,我希望它在有人直接访问 url 的情况下工作,例如http://domain.com/page.html#anchor
它在页面加载时从顶部平滑滚动到该锚点,现在它立即转到页面锚点,除非他们点击在锚上。我希望这是有道理的。