div在视口中时,addClass / removeClass到body

时间:2015-08-23 17:03:23

标签: jquery viewport addclass

<div id="title-box">
    <div class="title">Title</div>
</div>

<div id="gallery">
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
    <div class="gallery-image"></div>
    <div class="gallery-image"></div> 
</div>

<div id="text-box">
    <div class="text">
        One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin...
    </div>
</div>

我尝试了各种jQuery插件,但是我无法获得理想的结果。我想在视口中看到“ gallery ”元素时向 body 添加一个类,并删除 body 当“ gallery ”项目不再可见时。

我是jQuery的新手。

1 个答案:

答案 0 :(得分:1)

请尝试此

$(document).ready(function(){
    $('#gallery').bind('inview', function (event, visible) {

        if (visible == true) {
        // element is now visible in the viewport
            $('body').addClass('myclass');
        }
        else{
           $('body').removeClass('myclass');
           alert('removed... pleasecheck body');
        }  
    });
    $('#gallery').trigger('inview');
});

DEMO