在没有页面滚动的情况下修改document.location.hash [英] Modifying document.location.hash without page scrolling
问题描述
我们有一些页面使用ajax加载内容,并且在某些情况下我们需要深入链接到页面。而不是链接到用户并告诉人们点击设置,能够将人们链接到 user.aspx#settings
We've got a few pages using ajax to load in content and there's a few occasions where we need to deep link into a page. Instead of having a link to "Users" and telling people to click "settings" it's helpful to be able to link people to user.aspx#settings
为了让人们能够为我们提供正确的部分链接(用于技术支持等),我已将其设置为在点击按钮时自动修改URL中的哈希值。唯一的问题当然是当发生这种情况时,它也会将页面滚动到这个元素。
To allow people to provide us with correct links to sections (for tech support, etc.) I've got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element.
有没有办法禁用它?下面是我到目前为止这样做的方法。
Is there a way to disable this? Below is how I'm doing this so far.
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash=$(this).attr("id")
//return false;
});
});
我原本希望返回false;
会阻止页面滚动 - 但它只是使链接不起作用。所以我现在只是注释掉了所以我可以导航。
I had hoped the return false;
would stop the page from scrolling - but it just makes the link not work at all. So that's just commented out for now so I can navigate.
任何想法?
推荐答案
我想我可能找到了一个相当简单的解决方案。问题是URL中的哈希值也是您滚动到的页面上的元素。如果我只是在哈希前面添加一些文本,现在它不再引用现有元素了!
I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!
$(function(){
//This emulates a click on the correct button on page load
if(document.location.hash){
$("#buttons li a").removeClass('selected');
s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
eval(s);
}
//Click a button to change the hash
$("#buttons li a").click(function(){
$("#buttons li a").removeClass('selected');
$(this).addClass('selected');
document.location.hash="btn_"+$(this).attr("id")
//return false;
});
});
现在,网址显示为 page.aspx#btn_elementID
这不是页面上的真实ID。我只是删除btn_并获得实际的元素ID
Now the URL appears as page.aspx#btn_elementID
which is not a real ID on the page. I just remove "btn_" and get the actual element ID
这篇关于在没有页面滚动的情况下修改document.location.hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!