在没有页面滚动的情况下修改location.hash我们有一些页面使用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;会阻止页面滚动 - 但它只会使链接无法正常工作。所以现在只是注释掉,所以我可以导航。有任何想法吗?
3 回答
慕后森
TA贡献1802条经验 获得超5个赞
步骤1:您需要解除节点ID,直到设置了哈希。这是通过在设置哈希时从节点中删除ID,然后重新添加它来完成的。
hash = hash.replace( /^#/, '' );var node = $( '#' + hash );if ( node.length ) {
node.attr( 'id', '' );}document.location.hash = hash;if ( node.length ) {
node.attr( 'id', hash );}第2步:某些浏览器会根据上次看到ID'd节点的位置触发滚动,因此您需要稍微帮助它们。您需要div在视口顶部添加一个额外的内容,将其ID设置为哈希值,然后将所有内容回滚:
hash = hash.replace( /^#/, '' );var fx, node = $( '#' + hash );if ( node.length ) {
node.attr( 'id', '' );
fx = $( '<div></div>' )
.css({
position:'absolute',
visibility:'hidden',
top: $(document).scrollTop() + 'px'
})
.attr( 'id', hash )
.appendTo( document.body );}document.location.hash = hash;if ( node.length ) {
fx.remove();
node.attr( 'id', hash );}第3步:将其包装在插件中并使用它而不是写入location.hash...
白板的微信
TA贡献1883条经验 获得超3个赞
我想我可能找到了一个相当简单的解决方案。问题是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.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;
});});现在,URL显示为page.aspx#btn_elementID不是页面上的真实ID。我只是删除“btn_”并获取实际的元素ID
慕侠2389804
TA贡献1719条经验 获得超6个赞
使用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';
浏览器支持
添加回答
举报
0/150
提交
取消
