在当前位置获取div的ID [英] Getting the ID of the div at current position

查看:187
本文介绍了在当前位置获取div的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一页中有n个<section>.每个人都有一个ID,例如"page1","page2" ...

I have n number of <section> in a page. Each one is provided with id such as 'page1', 'page2'...

在顶部,我放置2个按钮,分别是上一个"和下一个".当按下Previous(上一个)时,它将滚动到上一个<section>.类似于按下下一步"按钮时的下一个<section>.

At the top I place 2 buttons say Previous and Next. When Previous is pressed it will be scrolled to the Previous <section>. Similarly to the next <section> on pressing Next Button.

但是现在的问题是,当用户使用滚动条滚动页面时,如何检测到用户正在查看哪个<section>?

But now the problem is when a user scrolls the page using the scroll bar, how can I detect which <section> the user is viewing?

推荐答案

您可以检查您的部分是否在"ViewPort"中,我正在使用它来查找:

You can check if your section is in the "ViewPort", i am using this to find out:

function isTotallyInViewPort($entry){
    var windowScrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var windowVisibleBottom = windowScrollTop + windowHeight;
    var entryTop = $entry.offset().top;
    var entryOuterHeight = $entry.outerHeight();
    var entryVisibleBottom = entryTop + entryOuterHeight;

    var isInView = windowScrollTop < ( entryTop ) < (windowVisibleBottom);
    if(!isInView) return false;

    var isCompleteInView = ( entryVisibleBottom ) < (windowVisibleBottom);
    return isCompleteInView;
}

如果要检测是否显示了PARTS,只需创建一个函数来检查当前视图是否与您的节的位置重叠.

if you want to detect if PARTS are shown, just create a function that checks if the current view is overlapping with the position of your section.

您可以将其绑定到$(window).on("scroll")

you may bind it to $(window).on("scroll")

我认为这应该可以检测您的元素是否已显示(尚未测试)

edit: i think this should detect if your elements are shown (not tested yet)

function isPartlyInViewPort($entry){
    var windowScrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var windowVisibleBottom = windowScrollTop + windowHeight;
    var entryTop = $entry.offset().top;
    var entryOuterHeight = $entry.outerHeight();
    var entryVisibleBottom = entryTop + entryOuterHeight;

    var isAboveViewPort = entryVisibleBottom < windowScrollTop;
    var isBelowViewPort = windowVisibleBottom < entryTop;

    return !(isAboveViewPort || isBelowViewPort);
}

这篇关于在当前位置获取div的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆