更改哈希时阻止页面滚动

时间:2012-04-26 13:37:36

标签: javascript jquery scroll hashtag

以下代码导致页面向下滚动到页面底部。在这种情况下如何防止页面滚动?

// If note is clicked, then append id as hashtag at end of url
$("span.note").click(function(e){
    e.preventDefault();
    window.location.hash = $(this).attr('id');
});

2 个答案:

答案 0 :(得分:0)

此外,您可以尝试添加:e.stopPropagation();

答案 1 :(得分:0)

要禁用滚动而不删除window.location中的哈希

您可以临时 删除节点的ID ,然后再更改 location.hash 然后,您再次在节点上设置 id

// Prevent default on anchor link click
$("a[href^='#']").click(function(e) {
    e.preventDefault();
    changeHashWithoutScrolling($(this).attr('href'));
});

// Prevent instant scroll of browser
function changeHashWithoutScrolling(hash){
    if($(hash).length > 0){
        var $el = $(hash);
        var elId = $el.attr('id');
        $el.removeAttr('id');

        window.location.hash = hash;

        $el.attr('id', elId);
    }
}
相关问题