微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery从不同的页面滚动到ID

我试图在一些页面内使用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”)
>在你的准备好的处理程序清除硬跳跃滚动通常由哈希表示,并尽快滚动页面回到顶部,并调用jump() – 你需要异步做
> in jump()如果没有给出事件,则使location.hash成为目标
>也有这种技术可能不赶上时间的跳跃,所以你会更好地隐藏html,身体,立即显示它,一旦你滚动回零

这是你的代码与上面添加

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
   },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中验证。 Dunno关于IE虽然。

原文地址:https://www.jb51.cc/jquery/184111.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐