Firefox-使用jQuery航路点滚动更新window.location.hash

Firefox - updating window.location.hash on scroll with jQuery waypoints

本文关键字:更新 window location hash 滚动 使用 jQuery 航路 Firefox-      更新时间:2023-09-26

BLUF:使用jQuery Waypoints用滚动到元素ID的方式更新location.hash会导致FF中的滚动冒泡/卡顿,但不会导致Chrome或IE中的滚动。

问题:当用户滚动具有以下基本布局的表时,我使用jQueryWaypoints来做一些事情:

____________________________________________________
| <tr class="category" id="cat1">Category One</tr> |
|   Cell          |    Cell       |   Cell         |
|   Cell          |    Cell       |   Cell         |
|   Cell          |    Cell       |   Cell         |
____________________________________________________
| <tr class="category" id="cat2">Category Two</tr> |
|   Cell          |    Cell       |   Cell         |
|   Cell          |    Cell       |   Cell         |
|   Cell          |    Cell       |   Cell         |

我想做的一件事是将视口顶部的.category行的ID附加到window.location。这个jQuery在Chrome 34和IE中工作,但在FF 28中,它会导致"冒泡"行为,即即使用户不断向下滚动,浏览器也会试图跳回来将元素放在视口的顶部。我在这里注释掉了preventDefault,因为尽管它修复了FF中的跳转,但它也阻止了脚本在到达第一个.category元素后更新哈希。有没有人在FF中更新location.hash时遇到过类似的问题,或者知道如何修复它?

$( '.category').waypoint(function() {
    //strip current hash from window.location
    window.location.hash.replace('#','');
    //store waypoint element's id
    var setHref = $(this).attr('id');
    //set id as location.hash
    window.location.hash = setHref;
    //e.preventDefault();
    return false;
}, { context: 'section' });

这是更改location.hash的核心功能:它会将您滚动到哈希引用的片段。使用location.hash无法绕过它。

对于相当现代的浏览器,您可以使用pushState或replaceState来操作URL和导航历史记录,而不会导致跳转到新推送的文档片段。