如何使用jQuery找到最接近当前位置的元素 [英] How to find the closest element to the current position with jQuery

查看:384
本文介绍了如何使用jQuery找到最接近当前位置的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下几个部分的文档:

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>

如何获取最近的< div.section> 到当前滚动位置(可能,这相当于读者当前正在查看的部分)?

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)?

推荐答案

你可以使用 $(窗口).scrollTop() $(el).postion()。top 计算出滚动后元素离屏幕顶部的距离。

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.

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

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

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

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

这篇关于如何使用jQuery找到最接近当前位置的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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