javascript 如何使用jQuery找到离当前位置最近的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10760567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:57:40  来源:igfitidea点击:

How to find the closest element to the current position with jQuery

javascriptjquery

提问by Scribblemacher

I have a document with several sections like this:

我有一个包含多个部分的文档,如下所示:

<div class='section' id='sec1'>
    lalala
    lalala
    lalala
</div>

<div class='section' id='sec2'>
    lalala
    lalala
    lalala
</div>

<div class='section' id='sec3'>
    lalala
    lalala
    lalala
</div>

<div class='section' id='sec4'>
    lalala
    lalala
    lalala
</div>

How do I grab the closest <div.section>to the current scroll position (presumably, this would equate to the section that the reader is currently looking at)?

我如何抓住最接近<div.section>当前滚动位置的位置(大概,这相当于读者当前正在查看的部分)?

回答by christurnerio

You can use $(window).scrollTop()and $(el).postion().topto figure out how far the element is from the top of the screen after scrolling.

您可以使用$(window).scrollTop()$(el).postion().top来计算滚动后元素距屏幕顶部的距离。

You can then use this information to manipulate the element as desired.

然后,您可以根据需要使用此信息来操作元素。

Here is a working jsfiddle example: http://jsfiddle.net/gizmovation/x8FDU/

这是一个有效的 jsfiddle 示例:http: //jsfiddle.net/gizmovation/x8FDU/

回答by Mihai Stancu

Whenever you hover an element the mousemoveevent tells you which element you're hovering over.

每当您将鼠标悬停在某个元素上时,该mousemove事件都会告诉您悬停在哪个元素上。

$(document).bind('mousemove', function(e) {
    e.target
    /*
        the target in click/hover events
        is the element that the event was
        triggered on.
    */
});

One drawback may be the fact e.targetwill give you the element with the highest z-index-- the one in the top-most layer -- so if you have an overlay above your text it will give you the overlay not the text div.

一个缺点可能是事实e.target会为您提供最高的元素z-index- 最顶层的元素- 所以如果您在文本上方有一个叠加层,它将为您提供叠加层而不是 text div