防止浏览器跳转到锚点

时间:2011-04-19 18:06:34

标签: javascript mootools anchor

如何阻止浏览器跳转到锚链接?

我知道我可以在onclick事件中使用“return false”,或者如果有人使用mootools做这样的事情

$('button').addEvent('click', function(e) {
e.stop()
//do blabla 
});

这将阻止浏览器跳转到锚点,但我想将锚点保留在URL中,以便可以共享链接。我实际上使用锚来显示动态信息。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

只需立即滚动回页面顶部即可。

self.scrollTo(0, 0)

我有一个插件可以做到这一点而且发生得太快我只是认为锚被打破了。我认为没有人会注意到。

答案 1 :(得分:2)

我还没有机会测试这个跨浏览器,所以它可能在IE中惨遭失败,但这里是我如何使用哈希链接更新URL,同时处理以不同方式单击它们时发生的实际操作(使用HTML5 history API):

var setHash = function(hash) {
    // Make sure that the hash is the first character, and extract from (presumably) full URL if not
    if (hash.indexOf('#') > 0) {
        hash = hash.substr(hash.lastIndexOf('#'));
    } else if (hash.substr(0, 1) !== '#') {
        hash = '#' + hash;
    }
    // Add our hash element to the history/URL
    if (window.history.pushState) {
        window.history.pushState(null, null, hash);
    } else {
        window.location = hash;
    }
};

$('button').addEvent('click', function(e) {
    e.stop()
    setHash(this.get('href'));
    //do blabla 
});