如何检测Html元素在View中? [英] How to detect that an Html element is in View?

查看:128
本文介绍了如何检测Html元素在View中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我从数据集中动态地创建一个菜单,并且使用jquery来检查一个元素是否在浏览器的可见客户区域内。并且当列表变长太长时,结果菜单的高度会导致它的一部分下降到浏览器底层客户区域之下。我怎么检测到这一点,并采取相应的行动? 我相信应该可以用 position() scrollTop() (add scrollLeft 如果你的页面容易水平滚动)。以下是一些未经测试的示例代码,如果目标元素(完全或部分)位于视口内,应显示一条消息:

  var pos = $('#element')。position(),win = $(window); 

if(pos.top< win.height()+ win.scrollTop()&& pos.bottom> win.scrollTop()){
alert('Look对我!');

$ / code>

如果您特别关心完全可见性,可以调换条件: p>

  if(pos.bottom< win.height()+ win.scrollTop()& pos.top> win .scrollTop()){

添加对视口水平滚动的支持作为练习阅读器:)

Using Jquery preferably, how do I detect if an element is within the viewable client area of a browser?

I'm dynamically creating a menu from a dataset, and when the list grows too long, the height of the resulting menu causes part of it to fall below the browser bottom client area. How do I detect this and act accordingly?

解决方案

I believe it should be possible to cook something up using position() and scrollTop() (add scrollLeft if your page is prone to horizontal scrolling). Here is some untested sample code that should display a message if the target element is (fully or partially) within the viewport:

var pos = $('#element').position(), win = $(window);

if (pos.top < win.height() + win.scrollTop() && pos.bottom > win.scrollTop()) {
    alert('Look at me!');
}

The conditions can be swapped around if you care specifically about full visiblity:

if (pos.bottom < win.height() + win.scrollTop() && pos.top > win.scrollTop()) {

Adding support for horizontal scrolling of the viewport is left as an exercise for the reader :)

这篇关于如何检测Html元素在View中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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