如何在页面加载后导航到主题标签? [英] How do I navigate to hashtag after page load?

查看:104
本文介绍了如何在页面加载后导航到主题标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做到目前为止我所发现的相反。我用js设置了很多高度,我想在页面加载后导航到url中的hashtag。我猜这很简单,但我没有看到明显的答案......例如,请点击这里......

I want to do the inverse of what I've been finding so far. I'm setting a lot of heights with js and I want to navigate to the hashtag in the url after the page has loaded. I'm guessing this is simple but I'm not seeing the obvious answer... for an example, check here...

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

试图这样做使用代码......

Attempted this using the code...

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

实际上并没有把我带到标记部分的顶部......

doesn't actually take me to the top of the tagged section...

推荐答案

如果您只是想在页面加载后更改哈希值:

If you simply want to change the hash after page loads:

window.onload = function (event) {
    window.location.hash = "#my-new-hash";
};

如果您想使用新哈希导航到网址:

If you want to navigate to the URL with new hash:

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

如果你想监听URL散列的变化;您可以考虑使用 window.onhashchange DOM事件。

If you want to listen for changes in the hash of the URL; you can consider using the window.onhashchange DOM event.

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

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

But it is not supported by every major browser yet. It now has a wide browser support. You can also check for changes by polling the window.location.hash on small intervals, but this is not very efficient either.

对于跨浏览器解决方案;我建议 Ben Alman的 jQuery hashchange插件 结合这些方法和其他一些具有回退机制的方法。

For a cross-browser solution; I would suggest Ben Alman's jQuery hashchange plugin that combines these methods and a few others with a fallback mechanism.

编辑:更新问题后,我知道您希望页面滚动到书签?:

After your question update, I understand you want the page to scroll to a bookmark?:

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

You can use Element.scrollTop or jQuery's $.scrollTop() method.

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

参见文档这里

这篇关于如何在页面加载后导航到主题标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆