我有这个代码用锚点动画我的页面
$('a[href*=#]').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
这个其他代码在链接出现时会延迟
function delay (URL) {
setTimeout( function() { window.location = URL }, 500 );
}
所以,当我有一个<a href="#demo">demo</a>
的链接时,第一个代码运行完全,但是当我添加像<a onclick="delay ('#contentexpand-1')">demo</a>
这样的延迟时,第一个代码不起作用,只是跳转到锚点。
请帮帮我!提前谢谢:)
答案 0 :(得分:0)
问题是您的动画已附加到<a>
标签。只需设置窗口位置即可触发。解决方案是以两种方式触发动画:
// Smoothly scroll to a tag defined by <a name="anchorName">
function scrollTo (anchorName) {
$('html, body').animate( {
scrollTop: $( "a[name=" + anchorName + "]" ).offset().top
}, 500);
}
// Make all # anchors scroll smoothly to their targets
$(document).ready(function(){
$('a[href*=#]').click(function() {
var anchorName = $(this).attr('href').substr(1); // strip off #
scrollTo(anchorName);
return false;
});
});
// Scroll to an anchor after half a second
function delay (anchorName) {
setTimeout( function() { scrollTo(anchorName); }, 500 );
}
我不相信你找到偏移量的代码是正确的,所以我调整了一下以使其更清晰。
您要滚动到的标记的定义如下:
<a name="demo">demo</a>
然后你可以选择任何一种行为:
<a href="#demo">scroll smoothly to demo immediately</a>
<a onclick="delay ('demo')">scroll smoothly to demo after half second delay</a>