14

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

用户访问我的网站(通过键入,而不是通过单击我页面上的链接) domain.com/bla.php#foo

and the anchor "#foo" exists. Now I want that the browser of the user does NOT automatically scroll to "#foo", instead I want to smoothly scroll so that the element '#foo' is about in the middle of the view and NOT on the absolute top position of the users view.

thanks so far!

4

9 回答 9

22

如果您不创建实际的锚点foo,而是使用类似_foo(类似<a id="_foo">)的 id 创建您的锚点。你可以处理$(document).ready来实现这一点。

类似的东西(伪代码)

$(document).ready(function() { 
    var elem = $('#_' + window.location.hash.replace('#', ''));
    if(elem) {
         $.scrollTo(elem.left, elem.top);
    }
});
于 2009-12-14T21:27:42.837 回答
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 的用户,该行为将保持不变。

于 2010-07-31T17:42:36.767 回答
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() {});

于 2012-08-27T13:05:03.290 回答
1

Machineghost 的回答非常有帮助。我拼凑在一起的代码采用 URL 参数并将其转换为哈希标记,然后浏览器会在 DOM 准备好后立即滚动到该标记。

URL 如下所示:

www.mysite.com/hello/world.htm?page=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”。

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

于 2012-01-04T20:46:58.887 回答
0

您仍然可以使用 ScrollTo。您可能希望呈现其中没有锚点的页面,然后使用在页面加载时运行的 JavaScript 从 URL 获取锚点。然后,您可以使用该文本滚动到特定 ID。

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

于 2009-12-14T21:28:39.323 回答
0

我不想说这是不可能的,但是……至少会很有挑战性。页面的那部分加载后,浏览器(或至少我知道的所有浏览器)滚动到锚点;AFAIK 没有基于 Javascript 的方法来避免这种情况(你需要一个浏览器插件或其他东西)。

但是,我认为您可能可以使用“在页面完全加载之前不显示页面”脚本的变体来获得您想要的行为。换句话说,你会:

  1. 隐藏所有页面的预加载内容(即,有一个包含整个页面的 DIV,并在其上放置“显示:无”样式)

  2. 将“onLoad”事件处理程序附加到取消隐藏 DIV 的页面,然后...

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

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

话虽如此,以上所有内容都是一个完全未经测试的计划;你的里程我的变化。即使它确实有效,实施起来也会很痛苦,所以除非你真的想要这种行为,否则几乎肯定不值得麻烦。

于 2009-12-14T21:29:57.683 回答
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');
    }
});
于 2019-12-11T10:16:15.613 回答
0
if(window.location.hash) {
  var hash = window.location.hash;

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

这对我来说很好..

于 2020-10-25T11:15:47.377 回答
-3

这是不可能的

编辑

行为完全掌握在 UA 手中。

于 2009-12-14T21:23:18.510 回答