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
How to find the closest element to the current position with jQuery
提问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().top
to 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 mousemove
event 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.target
will 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
。