0

How does one locate the nearest HTML fragment identifier (hashtag href) based on window's current scroll position?

I want to make a bookmarking feature via JS/jQuery that captures the nearest section the user was in when hitting the bookmark button. I don't have access to the backend, so I can't add any hooks/hidden fields, but that shouldn't matter because the fragment IDs are my hooks.

I'm thinking jQuery's .scroll() handler could be of use, but I'm not sure how to locate the "DOM content at a given scroll position" to know if a new identifier has appeared. Or if that's even the best approach...

Thoughts?

4

3 回答 3

2

像这样的东西:

$('a [href]').filter(function() {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(this).offset().top;
    var elemBottom = elemTop + $(this).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
})
.first();
于 2013-08-06T21:32:44.120 回答
1

虽然从技术上讲不是我最初问题的答案,但这是我决定使用的更灵活的解决方案:

当用户点击“书签”时,jQuery 将存储页面 url,并附加一个虚拟查询字符串,pos=X其中 X 是$('body').scrollTop().

当用户想要重新访问他的书签时,存储的 URL 将被加载,插入的 jQuery 将检索pos值并将页面滚动到书签位置。

这是理想的,因为它确实让用户回到了他/她离开的地方,直到像素。

于 2013-08-06T21:48:09.897 回答
0

我完全不明白你的问题,但要使用 jquery 在滚动上做一些事情,你可以试试这个。

$(document).ready(function(){
    $(window).scroll(function(){
        if ($(window).scrollTop() > 100){
            /*you check if identifier has appeared here*/
        }
    });
});
于 2013-08-06T21:28:21.063 回答