51

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

我希望这个想法很清楚。

谢谢

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

4

7 回答 7

66

你基本上需要这样做:

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

于 2012-03-21T13:36:31.460 回答
25

在链接上放一个哈希:

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

在其他页面上,您可以执行以下操作:

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

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

于 2012-03-11T06:35:19.950 回答
11

结合 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>
于 2012-10-26T04:33:53.747 回答
6

我想推荐使用 scrollTo 插件

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

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

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

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

于 2012-03-21T18:35:37.217 回答
2

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

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 不会做任何事情,所以当页面上的目标无法找到时,我们有一个很好的回退方法 yay \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);它只是将页面滚动到左上角。将其添加到上面的代码片段中。

于 2012-03-21T22:42:27.387 回答
2
function scroll_down(){
    $.noConflict();
    jQuery(document).ready(function($) {
        $('html, body').animate({
            scrollTop : $("#bottom").offset().top
        }, 1);
    });
    return false;
}

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

于 2012-03-25T17:34:40.577 回答
0

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

$('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;
  });
});
于 2017-09-12T12:12:03.857 回答