更改哈希时阻止页面滚动

问题描述 投票:1回答:2

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

// 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');
});
javascript jquery scroll hashtag
2个回答
0
投票

另外你可以尝试添加:e.stopPropagation();


0
投票

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

您可以在更改location.hash之前临时删除节点的ID。然后在节点上再次设置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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.