【问题标题】:jQuery scroll to ID from different pagejQuery从不同页面滚动到ID
【发布时间】:2012-03-28 00:27:02
【问题描述】:

我试图在一些页面中使用 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;
});

我希望这个想法很清楚。

谢谢

非常重要的注意事项: 我在上面发布的这段代码在同一页面内工作得很好,但我所追求的是单击一个页面中的链接并转到另一个页面,然后滚动到目标。我希望现在很清楚。谢谢

【问题讨论】:

  • 所以基本上这个想法是加载页面,我假设使用 ajax,然后平滑滚动到目标?比如你如何浏览acko.net上的页面?
  • 是的,类似这样,但在单击按钮之前不要加载页面。意思是先点击 url 移动到另一个页面,然后在页面加载后,它向下滚动到 div 元素。看起来有人已经回答了。

标签: jquery scroll smooth-scrolling


【解决方案1】:

你基本上需要这样做:

  • 在指向其他页面的链接中包含目标哈希 (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。

【讨论】:

  • 我已将工作示例上线:vostrel.cz/so/9652944/page.html 我还注意到,上面的脚本没有显示没有哈希的隐藏正文。通过在.ready() 中的条件中添加else 子句来修复它
  • 谢谢伙计。这是一个绝妙的解决方案。这正是我想要的。现在我可以自己添加任何效果。您首先获得了赏金积分,这是您应得的。
  • 很奇怪,当我尝试使用此代码时,我的整个页面都消失了?
  • @PetrVostrel 对我来说,您的链接在跳转到第二页时不会动画滚动。它立即跳转到 ID ......它真的对你有用吗?
  • 是的,对我也不起作用 - 如果有很多内容,页面会闪烁,然后就到达目标...
【解决方案2】:

在链接上放一个哈希:

<a href="otherpage.html#elementID">Jump</a>

在其他页面上,你可以这样做:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

在其他页面上,您应该将 id 设置为 elementID 的元素滚动到。当然你也可以改名字。

【讨论】:

  • 感谢您的回答。我会尝试一下,并在完成后提供一些反馈。再次感谢
  • 我试过了,但没有用。我想要么我错过了一些东西,要么有一些不正确的东西。我在 a href 链接 上做了一个哈希,但仍然不确定在哪里放置其他代码。而结果是,当我点击链接时,它直接进入了div处的页面,而不是滚动到它,这很奇怪。我相信代码与此有关,因此平滑滚动有效......知道如何解决这个问题吗?
  • 感谢大家的回复。每当我完成我现在手中的一切时,我都会检查你的所有答案。
  • 这对我有用。我为需要它的人评论它
  • @Sarfraz 如果可能的话你能检查一下这个stackoverflow.com/questions/56430914/…
【解决方案3】:

结合 Petr 和 Sarfraz 的答案,我得出以下结论。

在 page1.html 上:

<a href="page2.html#elementID">Jump</a>

在 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>

【讨论】:

    【解决方案4】:

    我想推荐使用 scrollTo 插件

    http://demos.flesler.com/jquery/scrollTo/

    您可以通过 jquery css 选择器设置滚动到。

    $('html,body').scrollTo( $(target), 800 );
    

    我对这个插件及其方法的准确性非常幸运,过去使用.offset().position() 等其他实现相同效果的方法对我来说都无法跨浏览器。并不是说你不能使用这样的方法,我确信有一种方法可以跨浏览器,我刚刚发现 scrollTo 更可靠。

    【讨论】:

    • 感谢您的回答。这个解决方案我知道并且我记得,它用于页面内的滚动,而不是从一个页面到另一个页面然后滚动到目标。抱歉,不过还是感谢您的尝试。
    • 只能在文档或文档元素内滚动。我不再理解您所说的“页面”是什么意思。您无法滚动到另一个文档。
    • 可能有点混乱。当您单击页面 A 上的链接转到页面 B 然后向下滚动到 div 元素。这是我想要实现的,但没关系,解决方案就在那里。感谢您的尝试
    • 是的,我的解决方案就是这样做的。不过不用担心,选择适合您的答案。
    • 我知道这是旧的但它不是滚动到更多使用插件来滚动.local
    【解决方案5】:

    我制作了一个可重复使用的插件,可以做到这一点...我将事件绑定留在了插件本身之外,因为我觉得对于这样一个小帮手来说太侵入了...。

    jQuery(function ($) {
    
        /**
         * This small plugin will scrollTo a target, smoothly
         *
         * First argument = time to scroll to the target
         * Second argument = set the hash in the current url yes or no
         */
        $.fn.smoothScroll = function(t, setHash) {
            // Set time to t variable to if undefined 500 for 500ms transition
            t = t || 500;
            setHash = (typeof setHash == 'undefined') ? true : setHash;
    
            // Return this as a proper jQuery plugin should
            return this.each(function() {
                $('html, body').animate({
                    scrollTop: $(this).offset().top
                }, t);
    
                // Lets set the hash to the current ID since if an event was prevented this doesn't get done
                if (this.id && setHash) {
                    window.location.hash = this.id;
                }
            });
        };
    
    });
    

    接下来,我们可以通过 onload 来执行此操作,检查散列,如果存在则尝试直接将其用作 jQuery 的选择器。现在我当时无法轻松测试它,但不久前我为生产站点制作了类似的东西,如果这不能立即奏效,请告诉我,我会研究我得到的解决方案。

    (脚本应该在 onload 部分)

    if (window.location.hash) {
        window.scrollTo(0,0);
        $(window.location.hash).smoothScroll();
    }
    

    接下来,我们将插件绑定到仅在其 href 属性中包含哈希的锚点的 onclick。

    (脚本应该在 onload 部分)

    $('a[href^="#"]').click(function(e) {
        e.preventDefault();
    
        $($(this).attr('href')).smoothScroll();
    });
    

    由于如果匹配失败,jQuery 不会做任何事情,我们有一个很好的后备方案,用于在页面上找不到目标时耶\o/

    更新

    当只有一个哈希时,可选的 onclick 处理程序滚动到顶部:

    $('a[href^="#"]').click(function(e) {
        e.preventDefault();
        var href = $(this).attr('href');
    
        // In this case we have only a hash, so maybe we want to scroll to the top of the page?
        if(href.length === 1) { href = 'body' }
    
        $(href).smoothScroll();
    });
    

    这里还有一个简单的 jsfiddle 演示页面内的滚动,onload 设置起来有点困难......

    http://jsfiddle.net/sg3s/bZnWN/

    更新 2

    因此,您可能会遇到窗口已经滚动到元素 onload 的问题。这解决了这个问题:window.scrollTo(0,0); 它只是将页面滚动到左上角。将其添加到上面的代码 sn -p 中。

    【讨论】:

    • 感谢您的回答。代码很好,但不能从不同页面使用到另一个页面,然后向下滚动到目标。再次感谢您的努力。
    • 如果是这样的话,您的想法对我们任何人来说都不是很清楚...如果您提炼问题,我愿意再试一次:|
    • 谢谢,但我听到任何答案都没有问题。如果赏金点过期,我将重新设置新的,因为这个问题对我很重要。再次感谢
    【解决方案6】:
    function scroll_down(){
        $.noConflict();
        jQuery(document).ready(function($) {
            $('html, body').animate({
                scrollTop : $("#bottom").offset().top
            }, 1);
        });
        return false;
    }
    

    这里的“底部”是您要滚动到的 div 标签 ID。要更改动画效果,您可以将时间从“1”更改为不同的值

    【讨论】:

    • 感谢@vijayrk 的回答。这段代码也是针对页面内的滚动,而不是从一页到另一页滚动的目标。
    • 那么这是否意味着您要在父页面中编写jquery以使效果发生在子页面上?即你有pageA,你有链接到pageB。 PageB 有一个名为“abc”的 div。那么是不是说你要在PageA中写jquery,这样当你点击PageB的时候,就需要在pageB中除abc呢?
    • 不是真的,伙计。我在页面 A 中有页面 B 的链接。当我单击该链接时,我转到页面 B 并向下滚动到 div 元素 C...
    【解决方案7】:

    我写了一些东西来检测页面是否包含被点击的锚点,如果没有,则转到正常页面,否则滚动到特定部分:

    $('a[href*=\\#]').on('click',function(e) {
    
        var target = this.hash;
        var $target = $(target);
        console.log(targetname);
        var targetname = target.slice(1, target.length);
    
        if(document.getElementById(targetname) != null) {
             e.preventDefault();
        }
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-120 //or the height of your fixed navigation 
    
        }, 900, 'swing', function () {
            window.location.hash = target;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      相关资源
      最近更新 更多