当类在视口中时显示元素 [英] show element when class is in viewport

查看:36
本文介绍了当类在视口中时显示元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让 div 仅在某个类的元素在视口中可见时才出现.

I'm trying to make a div only appear when elements of a certain class are visible in the viewport.

我几乎通过这个http://jsfiddle.net/blowsie/M2RzU/

$(document).ready(function(){
    $('.myclass').bind('inview', function (event, visible) {
      if (visible == true) {
        // element is now visible in the viewport
        $(this).removeClass('myclass');
          alert('found h2!')
      } else {
        // element has gone out of viewport
         $(this).addClass('myclass');
      }
    });
});

但正如您通过此编辑所看到的 http://jsfiddle.net/deenbag/6D9x5/ 每次具有该类的任何元素进入或退出视口时都会触发该事件,因此即使另一个具有相关类的元素可见,退出的元素也会关闭所需的效果.

but as you can see by this edit http://jsfiddle.net/deenbag/6D9x5/ the event is triggered every time the any element with the class enters or exits the viewport, thus an exiting element will turn off the desired effect even if another element with the relevant class is visible.

我也一直在使用这个插件,但不知道如何让它适用于我想做的事情.http://opensource.teamdf.com/visible/examples/demo-basic.html

i also have been messing with this plugin but couldn't figure out how to get it to apply to what i want to do. http://opensource.teamdf.com/visible/examples/demo-basic.html

推荐答案

只需跟踪数组中的可见元素:

Just keep track of the visible elements in an array:

var visibleEls = [];
$('.myclass').bind('inview', function (event, visible) {
    if (visible == true) {
        // element is now visible in the viewport
        if(!~visibleEls.indexOf(this)) visibleEls.push(this);
    } else {
        // element has gone out of viewport
        var i=visibleEls.indexOf(this);
        if(~i) visibleEls.splice(i, 1);
    }
    $('body').toggleClass('red', !!visibleEls.length);
});

演示

请注意,您可以将其简化为

Note that you could simplify it to

var counter = 0;
$('.myclass').bind('inview', function (event, visible) {
    counter += visible*2-1;
    $('body').toggleClass('red', !!counter);
});

但这可能更容易出错.

演示

这篇关于当类在视口中时显示元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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