检查div是否可以在窗口中查看? [英] Check if div is viewable in window?

查看:80
本文介绍了检查div是否可以在窗口中查看?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定导航的单页网站,并使用滚动脚本,非常类似于: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slider.html

I have a one page site with fixed navigation and using a scroll script, very similar to this: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slider.html

我正在寻找的是一种方法来检查窗口中可以看到哪些部分,以便在使用浏览器滚动条时设置导航器上的活动状态,任何想法?

What I'm looking for is a way to check what section is viewable in the window to set the active state on the nav when using the browsers scroll bar, any ideas?

推荐答案

以下是您需要的所有变量...

Here are all the variables you'll need...

var $myElt       = $('.myElement');      // whatever element you want to check
var $window      = $(window);            // the window jQuery element
var myTop        = $myElt.offset().top;  // the top (y) location of your element
var windowTop    = $window.scrollTop();           // the top of the window
var windowBottom = windowTop + $window.height();  // the bottom of the window

然后确保你的元素在窗口的范围内......

Then to make sure your element is within the window's range...

if (myTop > windowTop && myTop < windowBottom) {
    // element is in the window
} else {
    // element is NOT in the window
    // maybe use this to scroll... 
    // $('html, body').animate({scrollTop: myTop}, 300);
}

jQuery参考:

  • http://api.jquery.com/offset/
  • http://api.jquery.com/height/
  • http://api.jquery.com/scrollTop/

这篇关于检查div是否可以在窗口中查看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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