简体   繁体   中英

jQuery change single element from class

I'm using jQuery to check if an element is on screen. 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).

$(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.

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

If you show your full code, I can adapt that for you, but this should be easy to figure out now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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