gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:19:33 27 4
gpt4 key购买 nike

我们有一些页面使用 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/1489624/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com