我正在处理的结构是这样的:
<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;
});
}
}
});
});
最佳答案
在调用事件处理函数时获取 .offset()
,只需将 targetOffset
赋值放在函数中即可:
$(this).click(function() {
var targetOffset = $target.offset().top;
$('html, body').animate({scrollTop: targetOffset}, 600);
return false;
});
关于jquery - 如果页面高度动态变化,带 id 的链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26503034/