当div在浏览器窗口中可见时运行脚本 [英] Run script when div is visible in browser window

查看:91
本文介绍了当div在浏览器窗口中可见时运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当浏览器窗口中显示 div 时,我需要运行一些JavaScript,例如,当它滚动到,甚至重复时。我该怎么做呢?

I need to run some JavaScript when a div is visible in the browser window, for example, when it is scrolled to, even repeatedly. How would I go about doing so?

基本结构:

<div class='page1'></div>

<div class='page2'></div>

<div class='page3'></div>

<div class='page4'></div>

CSS:

div {
    float: left;
    height: 500px;
    width: 500px;
    margin: 50px 0;
    background: grey;
}

小提琴: http://jsfiddle.net/Q5BUe/1/

推荐答案

与其他提供的问题/解决方案一样,这里是完整的实现...

As with the other provided question/solution, here is the full implementation...

加载后,我们运行该函数以分配具有相应颜色的可见div。在jQuery滚动处理程序上,我们继续调用该函数来分配新的背景颜色。

Upon loading, we run the function to assign the visible divs with the corresponding color. On jQuery scroll handler, we continue to call the function to assign the new background color.

http://jsfiddle.net/Q5BUe/5 /

$(allInView);
$(window).scroll(allInView);


function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

function allInView() {

    if (isScrolledIntoView($(".page1"))) $(".page1").css("backgroundColor", "red");
    else $(".page1").css("backgroundColor", "grey");

    if (isScrolledIntoView($(".page2"))) $(".page2").css("backgroundColor", "green");
    else $(".page2").css("backgroundColor", "#333");

    if (isScrolledIntoView($(".page3"))) $(".page3").css("backgroundColor", "yellow");
    else $(".page3").css("backgroundColor", "#222");

    if (isScrolledIntoView($(".page4"))) $(".page4").css("backgroundColor", "blue");
    else $(".page4").css("backgroundColor", "#111");

}

这篇关于当div在浏览器窗口中可见时运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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