检查div是否可以在窗口中查看?

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

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

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

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 

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

 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参考:

使用$('#element').offset().top; 检测元素顶部。

$(window).scrollTop(); 检测当前滚动位置。

$(window).height(); 检测当前窗口高度。

在这些步骤之后,您实际上只需要一些简单的数学计算。

 function isScrolledIntoView(elem) { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)); } 

source: 滚动后检查元素是否可见

请参阅以下lazyload插件:

 http://plugins.jquery.com/files/jquery.lazyload.js__6.txt 

以注释“返回项目相对于当前视图的状态”开头的部分将检查元素在视口中是否可见。

如果您正在使用jQuery,请尝试检查文档位置

 $('html').position().top; 

例如:

 $(document).bind("scroll", checkLink); function checkLink(){ /* Position will checked out after 1 sec when user finish scrolling */ var s = setTimeout(function(){ var docHeight = $('html').position().top; var allLinks = $('.navigation a'); if ( docHeight < 0 && docHeight <= -1000 ) { allLinks.removeClass('active'); $('a.firstlink').addClass('active'); } else if ( docHeight < -1000 && docHeight <= -2000 ) { allLinks.removeClass('active'); $('a.secondlink').addClass('active'); } else { /* .... */ } $(document).bind("scroll", checkLink); }, 1000); $(document).unbind('scroll'); } 

但是你的例子中的人已经很久没有坚持这个了:)他们只是在点击时切换课程

 $('#navigation').localScroll(); $('#navigation li a').click( function () { $('#navigation li a').removeClass("active"); $(this).addClass("active"); });