javascript 当 div 在浏览器窗口中可见时运行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12322833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run script when div is visible in browser window
提问by Johnny Derp
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?
当 adiv
在浏览器窗口中可见时,我需要运行一些 JavaScript ,例如,当它滚动到,甚至重复时。我该怎么做?
Basic structure:
基本结构:
<div class='page1'></div>
<div class='page2'></div>
<div class='page3'></div>
<div class='page4'></div>
CSS:
CSS:
div {
float: left;
height: 500px;
width: 500px;
margin: 50px 0;
background: grey;
}
Fiddle: http://jsfiddle.net/Q5BUe/1/
回答by r0m4n
As with the other provided question/solution, here is the full implementation...
与其他提供的问题/解决方案一样,这里是完整的实现......
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.
加载后,我们运行该函数来为可见的 div 分配相应的颜色。在 jQuery 滚动处理程序上,我们继续调用函数来分配新的背景颜色。
$(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");
}
回答by chris
Since your implying your using jQuery you could be like
由于您暗示您使用 jQuery,您可能会像
if($('#element').is(':visible'))
{
//do your thing
}