Dig*_*ite 47 jquery scroll smooth-scrolling
我试图在一些页面内使用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;
});
Run Code Online (Sandbox Code Playgroud)
我希望这个想法很清楚.
谢谢
非常重要注意:我上面发布的这段代码在同一页面内工作得很好,但我所追求的是从一个页面单击一个链接然后转到另一个页面,然后滚动到目标.我希望现在很清楚.谢谢
Pet*_*rel 65
你基本上需要这样做:
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();
}
});
Run Code Online (Sandbox Code Playgroud)
已经过验证,可在Chrome/Safari,Firefox和Opera中使用.关于IE的Dunno虽然.
Sar*_*raz 23
在链接上放一个哈希:
<a href="otherpage.html#elementID">Jump</a>
Run Code Online (Sandbox Code Playgroud)
在其他页面上,您可以这样做:
$('html,body').animate({
scrollTop: $(window.location.hash).offset().top
});
Run Code Online (Sandbox Code Playgroud)
在其他页面上,您应该将id设置为的元素elementID滚动到.当然你可以改变它的名字.
结合Petr和Sarfraz的答案,我得出以下结论.
在page1.html上:
<a href="page2.html#elementID">Jump</a>
Run Code Online (Sandbox Code Playgroud)
在page2.html:
<script type="text/javascript">
$(document).ready(function() {
$('html, body').hide();
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
我想建议使用scrollTo插件
http://demos.flesler.com/jquery/scrollTo/
您可以通过jquery css选择器设置scrollto.
$('html,body').scrollTo( $(target), 800 );
Run Code Online (Sandbox Code Playgroud)
我对这个插件及其方法的准确性感到非常幸运,其中实现相同效果的其他方法,如使用.offset()或.position()过去未能成为浏览器.不是说你不能使用这样的方法,我敢肯定有一种方法可以跨浏览器,我发现scrollTo更可靠.