在不刷新页面的情况下,将锚点名称添加/删除到当前URL

48

我希望在单击事件中,能够将锚点名称“#on”附加/删除到当前URL中,而不需要重新加载页面,或者使用链接中的href =“#on”,因为它会使我的页面跳转

例如:http://www.example.com/page.html#on,这样我就可以检测访问该URL的用户并调用On()函数。

function On()
{   
   //append to current url the anchor "#on"                 
}

function Off()
{   
  //remove from the current url the anchor "#on"                    
}

$('.on').live('click', function() {
  On();
  return false;    
}); 


$('.off').live('click', function() {
  Off();
  return false;    
}); 
3个回答

75

你并不真正需要jQuery来实现这个,你可以使用location.hash来获取/设置锚点名称。如果你将它放在jQuery的ready函数中,你可以在其被设置为特定值时执行某些操作:

$(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){
        // Show the hash if it's set
        alert(hash);

        // Clear the hash in the URL
        location.hash = '';
    }
});

请注意,当删除哈希时,地址栏中可能会保留尾随的#。如果你想实时响应锚点的更改,可以将回调绑定到 hashchange 事件:

$(document).bind("hashchange", function(){
    // Anchor has changed.
});

如果你想在清除锚点时防止页面跳转到顶部,你可以将 hashchange 事件绑定到跳回之前的滚动位置上。查看这个例子:http://jsfiddle.net/yVf7V/

var lastPos = 0;

$('#on').click(function(){
    location.hash = 'blah';
});

$('#off').click(function(){
    lastPos = $(window).scrollTop();
    location.hash = '';
});

$(window).bind('hashchange',function(event){
    var hash = location.hash.replace('#','');
    if(hash == '') $(window).scrollTop(lastPos);
    alert(hash);
});

谢谢,伙计,现在它运行得很好,除了我想将location.hash设置为空的部分,正如你所说,它会保留URL末尾的#,并且会使我的页面跳到顶部...有点烦人,但我希望能找到一个解决方法。再次感谢 ;) - Adrian
3
我已经添加了跳跃问题的解决方案。 - DarthJDG

20

如果您正在使用jQuery,请尝试此代码

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

1
要注意浏览器对于历史记录API的支持 - http://caniuse.com/#search=pushstate(基本上,IE10+)。 - pospi
你能否将其纯粹地用JS写下来? - HamiD

1

调用 history.pushState({}, "", link) 与设置 window.location = "#foo" 类似,两者都会创建并激活与当前文档相关联的另一个历史记录条目。

请注意,即使新 URL 仅在其哈希中与旧 URL 不同,pushState() 也永远不会导致 hashchange 事件被触发。

const url = new URL(window.location);
url.hash = '#foo';
window.history.pushState({}, '', url);

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#examples

https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接