当元素出现在视口运行功能中时 [英] When element appears in the viewport run function

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

问题描述

我正在尝试编写一个函数,以便当我的element出现时,便在其上附加了一个函数.

I'm trying to write a function so that when my element comes into view a function is attached to it.

我的页面上有很多元素,element1element2element3,我想编写一个函数来检查其中的任何一个在视口中,而不是一个大的声明.

I have a range of elements on my page, element1, element2, element3 and I'd like to write a function that checks when either of these is in the viewport, rather than having a big if statement.

我只有以下内容似乎不起作用,什么也没发生?

I have the following only this doesn't seem to work, and nothing happens?

var $findme = $('.section').each();

function Scrolled() {
    var findmeOffset = $findme.offset(),
        findmeTop = findmeOffset.top,
        scrollTop = $(document).scrollTop(),
        visibleBottom = window.innerHeight;

    if (findmeTop < scrollTop + visibleBottom) {
        console.log('element is visible');
    }

}

function Setup() {
    var $top = $('#top'),
        $bottom = $('#bottom');

    $top.height(500);
    $bottom.height(500);

    $(window).scroll(function() {
        Scrolled();
    });
}

$(document).ready(function() {
    Setup();

});


演示

http://jsfiddle.net/Yh7x3/

推荐答案

这是一个不错的解决方案: jsfiddle .

Here is a woking solution: jsfiddle.

您的主要问题是,您在scroll事件处理程序中使用了$fimdme,这是导致它仅应用于第一个元素的原因.对没有参数的元素调用.each()完全无效.

Your main problem is that you were using $fimdme in you scroll event handler, what caused that it only applied to the first element. Calling .each() to an element with no arguments has no effect at all.

这是新代码.我对其进行了修改,因此,每次滚动时,无论是否向下滚动或向上滚动,警报都仅在现在(在视口中)可见且之前不可见的情况下显示该部分的文本.

Here's the new code. I modified it so, every time you scroll, the alert shows the text of a section if, and only if, it is visible now (in the viewport) and was not visible before, whether you scroll down or you scroll up.

var $findme = $('.section');

function Scrolled() {
    $findme.each(function() {
        var $section = $(this),
            findmeOffset = $section.offset(),
            findmeTop = findmeOffset.top,
            findmeBottom = $section.height() + findmeTop,
            scrollTop = $(document).scrollTop(),
            visibleBottom = window.innerHeight,
            prevVisible = $section.prop('_visible');

        if ((findmeTop > scrollTop + visibleBottom) ||
             findmeBottom < scrollTop) {
            visible = false;
        } else visible = true;

        if (!prevVisible && visible) {
            alert($section.text());
        }
        $section.prop('_visible', visible);
    });

}

function Setup() {
    var $top = $('#top'),
        $bottom = $('#bottom');

    $top.height(500);
    $bottom.height(500);

    $(window).scroll(function() {
        Scrolled();
    });
}

$(document).ready(function() {
    Setup();
});

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

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