javascript - 在不滚动页面的情况下修改 location.hash

标签 javascript jquery fragment-identifier

我们有一些页面使用 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.replaceStatehistory.pushState* 更改哈希。这不会触发跳转到相关元素。

例子

$(document).on('click', 'a[href^=#]', function(event) {
  event.preventDefault();
  history.pushState({}, '', this.href);
});

Demo on JSFiddle

* 如果你想要历史向前和向后支持

历史行为

如果您正在使用 history.pushState 并且您不希望在用户使用浏览器的历史记录按钮(向前/向后)时滚动页面,请查看实验性的 scrollRestoration 设置(仅限 Chrome 46+)

history.scrollRestoration = 'manual';

浏览器支持

关于javascript - 在不滚动页面的情况下修改 location.hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4653396/

相关文章:

javascript - JS变量等于html数据属性

javascript - 交易模板 $routeProvider 之后侧边栏不工作

javascript - 什么 jquery isArrayLike 检查 nodeType

javascript - 菜单打开时移动 View 问题?

javascript - 在 JQuery 中进行 URL 哈希/历史记录的最佳库是什么?

java - 从 URL 中检索片段(散列)并将值注入(inject) bean

javascript - 如何在使用 Angular-file-upload 上传之前修复 EXIF 方向

javascript - Node.js 身份验证 php auth_user

javascript - 启用输入选择但禁用文本输入

forms - 具有哈希更改功能的 jquery 表单插件