jQuery:调用URL时滚动到锚点,替换浏览器行为

14

我已经知道了jQuery插件ScrollTo,但是到目前为止我还没有找到任何方法来实现以下功能:

用户通过输入而不是在我的页面上点击链接进入我的网站 domain.com/bla.php#foo,并且锚点“#foo”存在。 现在我想让用户的浏览器不自动滚动到“#foo”,而是要平滑地滚动,使元素“#foo”大约位于视图中间位置,而不是在用户视图的绝对顶部位置。

感谢迄今为止的帮助!

9个回答

23
如果您不创建实际的锚点 foo,而是使用类似于 _foo 的id来创建您的锚点(例如 <a id="_foo">),则可以处理 $(document).ready 以实现此目的。
类似以下伪代码:
$(document).ready(function() { 
    var elem = $('#_' + window.location.hash.replace('#', ''));
    if(elem) {
         $.scrollTo(elem.left, elem.top);
    }
});

哇,这看起来非常不错!应该是可行的,非常感谢:) 唯一有点蠢的是:用户只有在完整页面加载后才会滚动。也许用户不想等那么长时间,自己滚动或者被烦恼了...但我肯定会试一下,目前为止非常感谢! - bj.
啊好的,你可以将jQuery插入所有HTML下面,不用等待文档完全加载,这样应该就能得到你想要的结果了 :-) - Jan Jongboom

6

我对Jan Jongboom的脚本进行了一些增强,现在它的样子是这样的:

$(document).ready(function () {
    // replace # with #_ in all links containing #
    $('a[href*=#]').each(function () {
        $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    });

    // scrollTo if #_ found
    hashname = window.location.hash.replace('#_', '');
    // find element to scroll to (<a name=""> or anything with particular id)
    elem = $('a[name="' + hashname + '"],#' + hashname);

    if(elem) {
         $(document).scrollTo(elem, 800);
    }

});

它更改所有链接中的锚点,因此对于没有启用JavaScript的用户,该行为将保持不变。

1

Machineghost的回答非常有帮助。我拼凑起来的代码接受URL参数并将其转换为哈希标签,然后浏览器在DOM准备就绪后滚动到该标签。

URL看起来像这样:

www.mysite.com/hello/world.htm?page=contact

Contact是您想要滚动到的ID名称

<h1 id="contact">Contact Us</h1>

这是代码:

// Get any params from the URL
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var url = decodeURIComponent(window.location.href);
    var hashes = url.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
 }
});

$(document).ready(function() {
    // Unhide the main content area
    $('section.centered').fadeIn('slow');

    // Create a var out of the URL param that we can scroll to
    var page = $.getUrlVar('page');
    var scrollElement = '#' + page;

    // Scroll down to the newly specified anchor point
    var destination = $(scrollElement).offset().top;
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-75}, 800 );
    return false;
});

我在Chrome和FF中测试了这个代码,它运作得非常好。如果滚动目标没有滚到您想要的确切位置,请尝试调整“destination-75”。

没有以上的帖子,我是无法做到的,所以谢谢!


1
/* scrolling to element */
    var headerHeight = $('#header').height() + $('#header-bottom-cap').height() + 10; //When the header position is fixed
    $('a').click(function(){
        var hashEle = $(this).attr('href').split('#');
        if (hashEle.length > 1) {
            if (hashEle[1] == 'top') {
                $('body, html').animate({
                    scrollTop: 0
                },500);
            } else {
            jQuery('body, html').animate({
                scrollTop: $('#'+ hashEle[1]).offset().top - headerHeight
            },500);
            }
        };
    })
        // find element from url
hashname = window.location.hash.replace('#', '');
elem = $('#' + hashname);
if(hashname.length > 1) {
    if(hashname == 'top') {
    $('body, html').animate({
            scrollTop: 0
        },200); 
    } else {
     $('body, html').animate({
            scrollTop: $(elem).offset().top - headerHeight
        },500);
 }
};
/* END scrolling to element */

这个脚本应该放在$(document).ready(function() {});中。


0

您仍然可以使用ScrollTo。您需要在页面中不使用锚点进行渲染,然后在页面加载时运行JavaScript来从URL获取锚点。然后,您可以使用该文本滚动到特定的ID。

不确定如何获取页面中间的项目,但是您可以为滚动指定偏移量。


0

我不想说这是不可能的,但是... 至少会非常具有挑战性。浏览器(或者至少我知道的所有浏览器)在页面加载时立即滚动到锚点;据我所知,没有基于Javascript的方法可以避免这种情况(你需要一个浏览器插件或其他东西)。

然而,我认为你可以使用一种“在页面完全加载之前不显示页面”的脚本变体来潜在地获得你想要的行为。换句话说,你应该:

  1. 在预加载之前隐藏页面的所有内容(即,在你整个页面周围放置一个DIV,并在其上放置“display:none”样式)

  2. 将“onLoad”事件处理程序附加到页面上,以取消隐藏你的DIV,并且...

  3. 在同一个“onLoad”事件处理程序中,使用标准的JS滚动机制(即ScrollTo)滚动到锚点(我认为你可以通过检查window.location来确定要滚动到哪个锚点)

理论上,因为浏览器将在#1和#2之间滚动(由于内容被隐藏,所以我想它根本不会做任何事情),您在#3中使用的滚动机制不应该有任何干扰。

话虽如此,以上所有内容都是一个完全未经测试的计划;你的结果可能会有所不同。即使它确实起作用,实现起来也会很麻烦,所以除非你真的需要这种行为,否则几乎肯定不值得麻烦。


0
if(window.location.hash) {
  var hash = window.location.hash;

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

这对我来说很好用。


0

尝试使用jQuery,这段代码对我来说完美无瑕。

$(document).ready(function() {
    var target = window.location.hash;
    var offset = 85; // You can change this value as per your need.
    if ($(target).length > 0) {
        $('html, body').animate({
            scrollTop: $(target).offset().top - offset
        }, 1000);
    } else {
        console.warn('Element ' + target + ' does not exist');
    }
});

-3

这是不可能的

编辑

行为完全由UA控制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接