简体   繁体   中英

How to change the scrolling position?

I want to have my content fade in on scrolling, but it reacts to late. How can I change it, to have my content fade in earlier?

I am very new to javascript and couldn't get it worked yet.

$(window).on("load",function() {
  $(window).scroll(function() {
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();
    $(".fade").each(function() {
      /* Check the location of each desired element */
      var objectBottom = $(this).offset().top + $(this).outerHeight();

      /* If the element is completely within bounds of the window, fade it in */
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
      } else { //object goes out of view (scrolling up)
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
      }
    });
  }).scroll(); //invoke scroll-handler on page-load
});

Right now the content space is blank until I scroll to the bottom. I need to have my content fade in when it is on like half of the page or earlier. Maybe changeable to any height with percent or pixel?

The shared portion of code fades element in once they are completely in the viewport (= when bottom of the elements is in the window).

How about fading elements in as soon as their tops get in the viewport?

Fade out logic should remain as is: elements should be faded out once their bottom get out of the viewport.

Adapted code:

$(window).on("load",function() {
  $(window).scroll(function() {
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();
    $(".fade").each(function() {
      /* Check the location of each desired element */
      var objectTop = $(this).offset().top
          , objectBottom = $(this).offset().top + $(this).outerHeight();

      /* If the element's top gets within bounds of the window, fade it in */
      if (objectTop < windowBottom) { //object comes into view (scrolling down)
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
      } else if (objectBottom >= windowBottom){ //object goes out of view (scrolling up)
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
      }
    });
  }).scroll(); //invoke scroll-handler on page-load
});

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