我正在处理的结构如下:
<html>
<header>
<a href="#footer">scroll to footer</a>
</header>
<section id="gallery"></section>
<footer id="footer"></footer>
</html>
很明显,我希望在点击链接时滚动到#footer
,但问题是#gallery
是在页面加载后加载的,整个页面的高度会发生变化。链接仅滚动到加载#gallery
之前#footer
所在的位置。
我使用的图库示例:http://tympanus.net/Development/GammaGallery/
我用来平滑滚动的jQuery代码:
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(//$/,'');
}
$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 600);
return false;
});
}
}
});
});
当事件处理程序函数被调用时,只需将targetOffset
赋值放在函数中即可获得.offset()
:
$(this).click(function() {
var targetOffset = $target.offset().top;
$('html, body').animate({scrollTop: targetOffset}, 600);
return false;
});