1

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

// 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');
});
4

2 回答 2

0

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

于 2012-04-26T13:41:13.110 回答
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);
    }
}
于 2019-04-30T14:32:19.130 回答