javascript 仅为视图中的元素添加类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22326971/
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
Add class only for the element in view
提问by euDennis
I was looking for something like the affect of this page(I'm looking for the trigger that start the animations with the scroll of the page)
我正在寻找类似于此页面的影响的东西(我正在寻找通过页面滚动启动动画的触发器)
Some people help me here in StackOverFlow with this code:
有些人在 StackOverFlow 中使用以下代码帮助我:
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));
}
$(window).scroll(function(){
if (isScrolledIntoView('.class') === true) {
$('.class').addClass('in-view')
}
});
The result can be found here: http://jsfiddle.net/z3xTU/
结果可以在这里找到:http: //jsfiddle.net/z3xTU/
But now I got another problem. I have a page with several DIVs, I want to animate all of them, but if I set every with ".class", this code add the "in-view" for all of they, at the same time. This trigger all the animation to start when the first div come to view, isn't what I'm looking for.
但是现在我遇到了另一个问题。我有一个包含多个 DIV 的页面,我想为所有 DIV 设置动画,但是如果我将每个设置为“.class”,则此代码会同时为所有这些 DIV 添加“in-view”。当第一个 div 出现时,这会触发所有动画开始,这不是我想要的。
Anyone have a better idea that can help me?
任何人都有更好的主意可以帮助我?
回答by Jai
Try this:
试试这个:
$(window).scroll(function () {
$('.class').each(function () {
if (isScrolledIntoView(this) === true) {
$(this).addClass('in-view')
}
});
});
Loop through all your elems and pass the current context in the function isScrolledIntoView(this)
, so here this
is your current elemwhich is available in view.
循环遍历所有 elems 并在函数中传递当前上下文isScrolledIntoView(this)
,因此这this
是您当前可用的elem。
Fiddle
小提琴
回答by yunzen
Use different classes for the different elements or use ids.
为不同的元素使用不同的类或使用 id。
$(window).scroll(function(){
if (isScrolledIntoView('.class1') === true) {
$('.class1').addClass('in-view')
}
if (isScrolledIntoView('.class2') === true) {
$('.class2').addClass('in-view')
}
});
or
或者
$(window).scroll(function(){
if (isScrolledIntoView('#id1') === true) {
$('#id1').addClass('in-view')
}
if (isScrolledIntoView('#id2') === true) {
$('#id2').addClass('in-view')
}
});