如何更改滚动位置?

时间:2019-04-15 10:36:26

标签: javascript

我想让我的内容在滚动时淡入,但它会延迟到最后。如何更改它,以使内容早些消失?

我对javascript很陌生,还无法正常工作。

$(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
});

现在,内容空间为空白,直到我滚动到底部。当内容在页面的一半或更早的位置时,我需要淡入内容。也许可以更改为具有百分比或像素的任何高度?

1 个答案:

答案 0 :(得分:0)

代码的共享部分在元素完全位于视口中时使它们淡入(=当元素底部位于窗口中时)。

当元素的顶部进入视口时如何使其褪色?

淡出逻辑应保持不变:元素底部离开视口后应淡出。

自适应代码:

$(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
});