CBa*_*arr 143 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;
});
});
Run Code Online (Sandbox Code Playgroud)
我曾希望return false;
会阻止页面滚动 - 但它只会使链接无法正常工作.所以现在只是注释掉,所以我可以导航.
有任何想法吗?
Bor*_*gar 110
步骤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 );
}
Run Code Online (Sandbox Code Playgroud)
第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 );
}
Run Code Online (Sandbox Code Playgroud)
第3步:将其包装在插件中并使用它而不是写入location.hash
...
HaN*_*riX 90
使用history.replaceState
或history.pushState
*更改哈希值.这不会触发跳转到相关元素.
$(document).on('click', 'a[href^=#]', function(event) {
event.preventDefault();
history.pushState({}, '', this.href);
});
Run Code Online (Sandbox Code Playgroud)
*如果您想要历史向前和向后支持
如果您正在使用history.pushState
并且当用户使用浏览器的历史记录按钮(向前/向后)时您不想要页面滚动,请查看实验scrollRestoration
设置(仅限Chrome 46+).
history.scrollRestoration = 'manual';
Run Code Online (Sandbox Code Playgroud)
CBa*_*arr 89
我想我可能找到了一个相当简单的解决方案.问题是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;
});
});
Run Code Online (Sandbox Code Playgroud)
现在,URL显示为page.aspx#btn_elementID
不是页面上的真实ID.我只是删除"btn_"并获取实际的元素ID
归档时间: |
|
查看次数: |
110346 次 |
最近记录: |