我们有一些页面使用 ajax 来加载内容,并且在某些情况下我们需要深入链接到页面。与其拥有指向“用户”的链接并告诉人们单击“设置”,不如将人们链接到 user.aspx#settings
为了让人们能够向我们提供正确的部分链接(用于技术支持等),我将其设置为在单击按钮时自动修改 URL 中的散列。当然,唯一的问题是,发生这种情况时,它还会将页面滚动到该元素。
有没有办法关闭它?以下是我目前的做法。
$(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;
});
});
我曾希望 return false;
会停止页面滚动 - 但它只是让链接根本不起作用。所以现在只是注释掉了,这样我就可以导航了。
有什么想法吗?
最佳答案
使用 history.replaceState
或 history.pushState
* 更改哈希。这不会触发跳转到相关元素。
例子
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);
});
* 如果你想要历史向前和向后支持
历史行为
如果您正在使用 history.pushState
并且您不希望在用户使用浏览器的历史记录按钮(向前/向后)时滚动页面,请查看实验性的 scrollRestoration
设置(仅限 Chrome 46+)。
history.scrollRestoration = 'manual';
浏览器支持
- > replaceState
- > pushState
- > polyfill
关于javascript - 在不滚动页面的情况下修改 location.hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13938788/