简体   繁体   English

如何更改滚动位置?

[英]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.我对 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
});

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

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

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