简体   繁体   English

jQuery从类更改单个元素

[英]jQuery change single element from class

I'm using jQuery to check if an element is on screen. 我正在使用jQuery检查屏幕上是否有元素。 I'm selecting the element by it's class since I have multiple elements that should do the same but at different moments. 我要按其类选择元素,因为我有多个元素应该在相同的时刻执行相同的操作。 When one element is on screen I'm changing it (fadeIn + animated slide up). 当一个元素在屏幕上时,我正在对其进行更改(fadeIn +动画向上滑动)。

$(window).scroll(function(){
  $(".material-slide-up").each(function(){
    if(isScrolledIntoView($(this))) {
      $(this).fadeIn(1000);
      $(this).addClass("slideInUp animated");
    }
  });
});

When I run the current code all the elements with the same class are changed. 当我运行当前代码时,具有相同类的所有元素都会更改。 I think it's because I'm using "each". 我认为这是因为我正在使用“每个”。

Is there a way to only change one element from the same class that is on screen? 有没有办法只更改屏幕上同一类的一个元素?

A little helper function like this is great 像这样的小助手功能很棒

$.fn.inView = function(){
if(!this.length) return false;
var rect = this.get(0).getBoundingClientRect();

return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight ||  document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);

};

Now, you did not share your DOM, so we will use mine, here is the link to the pen, scroll down to see the effect. 现在,您尚未共享DOM,因此我们将使用我的DOM,这是笔的链接,向下滚动以查看效果。

The calling function should look like this 调用函数应如下所示

 $(window).on('scroll',function(){ 
 var imgs = $('img');
 imgs.each(function(){
    var $this = $(this);
    $this.inView() && $this.addClass('magictime vanishIn');
}) ;
});

http://codepen.io/damianocel/pen/zBLEXR http://codepen.io/damianocel/pen/zBLEXR

If you show your full code, I can adapt that for you, but this should be easy to figure out now. 如果您显示完整的代码,我可以为您改编,但是现在应该很容易理解了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM