当锚在URL中时,避免页面滚动/跳转 [英] Avoid the page scrolling/jumping when anchor is in the URL

查看:98
本文介绍了当锚在URL中时,避免页面滚动/跳转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

jquery - 加载页面时禁用锚点跳转

我正在显示一个div,具体取决于URL中的哈希值,但我想避免页面跳转到具有该特定ID的div的位置。

I'm displaying a div depending on the hash value in a URL but i want to avoid the page jumping to the postion of that div with that particular ID.

当页面直接使用URL中的哈希值导航时,我只会遇到问题,所以例如,如果某人有书标记了该页面。

I only have the problem when the page is navigated direct with the hash in the URL so say for example if someone has book marked the page.

例如,我有网址
domain.com/page.html#myitem-1

So for example I have the url domain.com/page.html#myitem-1

ID = myitem-然后会显示1,但是页面然后跳转到我不想要的div的位置。

ID=myitem-1 will then display, which it does but the page then jumps down to the postion of that div which i don't want.

我试图使用scrollTop(0 )强制窗口位置回到顶部但看起来好像在锚点跳转发生之前调用它没有效果

I was trying to use scrollTop(0) to force the window position back to the top but it seems as if this gets called before the anchor jump takes place to has no effect

示例代码:

  $(document).ready(function() {
    $('.glossary-term').hide();
    $(window.location.hash).show();

    $(window).scrollTop(0);

});

我能够让这个scrollTop工作的唯一方法是将它放在一个setTimeOut中持续时间为1,但这似乎有点像黑客。还有其他任何建议吗?

The only way i was able to get this scrollTop to work was to place it in a setTimeOut with a duration of 1, but this seems like a bit of a hack. Any other suggestions?

谢谢

B

推荐答案

好吧,如果你的内部机制只是用于显示div,你可以随时改变(或删除)name属性,这样浏览器就不会直接找到它并赢了试着滚动;)

Well, if it is your internal mechanism for using anchors just for displaying divs you can always change (or remove) the "name" attribute so the browser won't find it directly and won't try to scroll ;)

否则尝试如何禁用锚点跳转加载页面时?

这篇关于当锚在URL中时,避免页面滚动/跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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