在滚动时检测主要位于视口/中心的DIV [英] Detecting a DIV that is mostly in the viewport/center as you scroll

查看:60
本文介绍了在滚动时检测主要位于视口/中心的DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试知道元素在视口中最明显的时间,并且主要位于中心。我希望让所有其他div消失,但在滚动时保持更加显着的DIV完全不透明。



我发现:或这可以通过Digital Fusion 但是基本上你只需要测试一个元素是否完全在视图中并为其添加一个类。



所有相对简单(虽然我承认没有测试过这个x浏览器所以YMMV):

  function testInView($ el){
var wTop = $(window).scrollTop();
var wBot = wTop + $(window).height();
var eTop = $ el.offset()。top;
var eBot = eTop + $ el.height();
return((eBot< = wBot)&&(eTop> = wTop));
}
函数setInView(){
$(div)。each(function(){//测试每个div(你可能希望在你的实现中更具体)
var $ zis = $(this);
$ zis.removeClass(inview);
if(testInView($ zis)){
$ zis.addClass(inview) );
}
});
}
$(document).scroll(function(){
setInView();
});
$(document).resize(function(){
setInView();
});
$(document).ready(function(){
setInView();
});

这是jsFiddle


Trying to know when an element is most visible in the viewport and is mostly in the center. I'd like to have all the other divs fade off but keeping the more dominant DIV at full opacity as you scroll.

I found this: http://patik.com/code/within-viewport/ but it's by pixel and doesn't have the logic I require for this to work like in the image below.

解决方案

You would need a method that tested whether an element was fully within the bounds of the page. There are plugins that do this such as Remy Sharp's Element in-view Event Plugin or this by Digital Fusion but essentially you just need to test if an element is fully in view and add a class to it.

All relatively simple (although I confess to have not tested this x-browser so YMMV):

function testInView($el){
    var wTop = $(window).scrollTop();
    var wBot = wTop + $(window).height();
    var eTop = $el.offset().top;
    var eBot = eTop + $el.height();
    return ((eBot <= wBot) && (eTop >= wTop));
}
function setInView(){
    $("div").each(function(){//testing EVERY div (you might want to be more specific in your implementation)
        var $zis = $(this);
        $zis.removeClass("inview");
        if(testInView($zis)){
           $zis.addClass("inview");   
        }
    });
}
$(document).scroll(function(){
    setInView();
});
$(document).resize(function(){
    setInView();
});
$(document).ready(function(){
    setInView();
});

Here's the jsFiddle

这篇关于在滚动时检测主要位于视口/中心的DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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