jQuery + window.location.hash 和同页锚点 - 不一致的行为

jQuery + window.location.hash and same-page anchors - inconsistent behavior?

本文关键字:不一致 window location hash jQuery      更新时间:2023-09-26

考虑以下JS代码:

<script type="text/javascript">
$(function() {
    // Check if landing on the page with a hash
    if (window.location.hash.length) {
        $('html,body').animate({scrollTop: 200}, 100);
        return false;
    }
    // Same-page anchors
    $('a[href*=#]').click(function() {
        // ... find the target based on the div and animate the scrollTop property again
       }
    });
}); 
</script>

它的作用是首先检查是否登陆具有 #anchor 的页面,或者用户是否单击了同一页面 #anchor,然后简单地使用相应 id 对目标div 进行动画处理。

问题是这 2 个交替工作:如果您登陆带有哈希符号的页面,该页面将动画化为div ID,但随后的同页链接不会被绑定的"click"事件拦截(我也尝试过将其与 live() 绑定,没有区别)

如果您使用干净的URL登陆页面,则链接将再次起作用。我做错了什么?

为什么返回 false?这没有任何意义,因为在"ready"事件处理程序中,没有可以阻止的默认行为或将冒泡的 DOM 树。此外,它还会阻止执行以下语句(特别是将事件处理程序绑定到链接)。

if (window.location.hash.length) {
    $('html,body').animate({scrollTop: 200}, 100);
    return false;  // <-- remove this line!
}