jQuery fade out elements as they scroll off page, fade back as they scroll back on

故事扮演 提交于 2019-11-29 04:19:53

You can use attribute selector '[attr="someattr"]' with use of .each() method of jQuery:

$(window).scroll(function () {
   $('[id^="box"]').each(function () { // <---loop the divs id starts with #box 
      if (($(this).offset().top - $(window).scrollTop()) < 20) { //<---mark the $(this).offset().top of current object
          $(this).stop().fadeTo(100, 0); //<----fadeOut the current obj
      } else {
          $(this).stop().fadeTo('fast', 1); //<----fadeIn the current obj
      }
   });
});

You can take a demo here:

DEMO

This version of your jsfiddle is considered better for several reasons:

  • Well functionally decomposed (its broken into little functions): higher readability for you and other coders, and easier to maintain in the future if you need to change something.
  • Flexibility: you can change the number of boxes, without even knowing the javascript!
  • Efficiency: due to functional decomposition, it means that each line of code only gets called if 100% necessary

Apart from the javascript, i added classes in addition to existing id's. eg: id="box1" class="box"

enjoy :)

Well, I guess just set a class for all your divs. Instead of calling each one with an #id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!