页面加载后如何导航到特定的hashtag?

18

我希望做到与目前搜索的相反操作。我正在使用js设置许多高度,并且希望在页面加载后导航到url中的hashtag。我猜这很简单,但我没有看到明显的答案... 例如,请查看这里...

http://alavita.rizenclients.com/#story

尝试使用以下代码来实现...

$(window).load(function() {
    var hashTag = window.location.hash;
    window.location = '/' + hashTag;
}); 

无法将我实际带到所标记部分的顶部...


最终我使用了yepnope的complete函数链式调用。jQuery在内容被填充之前获取了hashtag偏移量的值。我刚刚在complete函数上混合了你们帮忙的代码。 - brunam
5个回答

37
如果您只想在页面加载后更改哈希值:
window.onload = function (event) {
    window.location.hash = "#my-new-hash";
};

如果你想要导航到带有新哈希值的URL:

window.location.href = "http://website.com/#my-new-hash";

如果您想监听URL的哈希变化,可以考虑使用window.onhashchange DOM事件。

window.onhashchange = function () {
    if (location.hash === "#expected-hash") {
        doSomething();
    }
};

但它目前还不被每个主流浏览器支持。它现在有广泛的浏览器支持。您还可以通过轮询小间隔的window.location.hash来检查更改,但这也不是非常有效。

对于一个跨浏览器解决方案,我建议使用Ben Alman的jQuery哈希变化插件结合这些方法和其他一些方法以及一个回退机制。

编辑:根据您的问题更新,我理解您想让页面滚动到书签处:

您可以使用Element.scrollTop或jQuery的$.scrollTop()方法。

$(document).ready(function (event) {
    var yOffset = $("#my-element").offset().top;
    $("body").scrollTop(yOffset);
});

点击这里查看文档。


2

由于某些原因,无论是 MS Edge 42 还是 IE 11,都不能在我设置新书签后滚动到新书签处,即使在执行 window.location.reload(true) 后也不行。因此,我想出了这个解决方案:在您加载的页面中插入此脚本(需要jquery)。

$(document).ready(function() {
 var hash = window.location.hash;
 if (hash) {
  var elem = document.getElementById(hash.substring(1));
  if (elem) {
   elem.scrollIntoView();
  }
 }
});

1
使用scrollToscrollIntoView将不会考虑由:target css选择器创建的任何偏移量,该选择器通常用于通过将其设置为position:relative和负top来使页面向上滚动到锚点的上方。
这将滚动到锚点同时考虑:target选择器:
if (location.hash) {
    window.location.replace(location.hash);
}

0
你可以直接设置当前位置:
window.location = 'http://alavita.rizenclients.com/#story';

或者设置哈希(如果还没有),然后重新加载:

window.location.hash = hashTag;
window.location=window.location.href;

即使运行这段代码:[code]$(window).load(function() { var hashTag = window.location.hash; window.location = '/' + hashTag; }); 实际上也无法将我带到标记部分的顶部... - brunam

0

你改变了你的问题。

看看这个解决方案。https://dev59.com/GnI95IYBdhLWcg3wxA8-#2162174,这样你就能理解发生了什么以及如何实现跨浏览器的解决方案。

注意:在底部他提到了一个 jQuery 插件,可以满足你的需求。

http://benalman.com/projects/jquery-hashchange-plugin/

这个插件将允许你做类似于这样的事情。它将适用于您当前的页面。但是您可能希望修改它以使其更加强大。

$(function(){

    // Bind the event.
    $(window).hashchange( function(){
        // get the hash
        var hash = window.location.hash;
        // click for your animation
        $('a[href=' + hash + ']').click();
    })

    // Trigger the event (useful on page load).
    $(window).hashchange();

});

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