我尝试在某些页面中使用 jQuery 的页面滚动,并且可以成功地实现平滑的页面滚动。我现在遇到的唯一问题是尝试从不同页面执行此操作时。我的意思是,如果我单击页面中的链接,它应该加载新页面,然后滚动到特定的 div 元素。
这是我用来在页面内滚动的代码:
var jump=function(e)
{
//prevent the "normal" behaviour which would be a "hard" jump
e.preventDefault();
//Get the target
var target = $(this).attr("href");
//perform animated scrolling
$('html,body').animate(
{
//get top-position of target-element and set it as scroll target
scrollTop: $(target).offset().top
//scrolldelay: 2 seconds
},2000,function()
{
//attach the hash (#jumptarget) to the pageurl
location.hash = target;
});
}
$(document).ready(function()
{
$('a[href*=#]').bind("click", jump);
return false;
});
我希望这个想法是清楚的。
谢谢
非常重要的注意: 我上面发布的这段代码在同一页面中效果很好,但我想要的是单击一个页面中的链接并转到另一个页面,然后滚动到目标。我希望现在一切都清楚了。谢谢
最佳答案
你基本上需要这样做:
- 将目标哈希包含到指向其他页面的链接中 (
href="other_page.html#section"
) - 在您的
ready
处理程序中清除通常由哈希决定的硬跳转滚动,并尽快将页面滚动回顶部并调用jump()
- 您需要异步执行此操作 - 在
jump()
中,如果没有给出事件,则将location.hash
作为目标 - 此外,这种技术可能无法及时捕捉到跳跃,因此您最好立即隐藏
html,body
并在将其滚动回零后将其显示出来
这是添加了上述内容的代码:
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
已验证可在 Chrome/Safari、Firefox 和 Opera 中运行。不过我不了解 IE。
关于jQuery从不同页面滚动到ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9652944/