向下滚动时淡入,向上滚动时淡出 - 基于窗口中的元素位置 [英] Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

查看:21
本文介绍了向下滚动时淡入,向上滚动时淡出 - 基于窗口中的元素位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一系列元素在窗口中完全可见时,我试图让它们在向下滚动时淡入.如果我继续向下滚动,我不希望它们淡出,但是如果我向上滚动,我确实希望它们淡出.

这是我找到的最接近的 jsfiddle.http://jsfiddle.net/tcloninger/e5qaD/

$(document).ready(function() {/* 每次滚动窗口时... */$(窗口).滚动(功能(){/* 检查每个所需元素的位置 */$('.hideme').each(function(i){var bottom_of_object = $(this).position().top + $(this).outerHeight();var bottom_of_window = $(window).scrollTop() + $(window).height();/* 如果对象在窗口中完全可见,则淡化它 */if(bottom_of_window >bottom_of_object ){$(this).animate({'opacity':'1'},500);}});});});

它在向下滚动时完全符合我的要求,但我也希望元素在我向上滚动时淡出.

我没有运气就试过了.

 if(bottom_of_window >bottom_of_object ){$(this).animate({'opacity':'1'},500);} 别的 {$(this).animate({'opacity':'0'},500);}

非常感谢您花时间看这个.

解决方案

您的尝试没有奏效的原因是因为两个动画(淡入和淡出)相互冲突.

就在对象变得可见之前,它仍然不可见,因此会运行淡出动画.然后,在同一对象变得可见的几分之一秒后,淡入动画将尝试运行,但淡出仍在运行.所以它们会相互对抗,而你什么也看不到.

最终对象会变得可见(大部分时间),但这需要一段时间.如果您使用滚动条按钮上的箭头按钮向下滚动,动画就会起作用,因为您将使用更大的增量滚动,从而减少滚动事件.

<小时>

解释够了,解决方案(JS、CSS、HTML):

$(window).on("load",function() {$(窗口).滚动(功能(){var windowBottom = $(this).scrollTop() + $(this).innerHeight();$(".fade").each(function() {/* 检查每个所需元素的位置 */var objectBottom = $(this).offset().top + $(this).outerHeight();/* 如果元素完全在窗口范围内,则将其淡入 */if (objectBottom < windowBottom) {//对象进入视图(向下滚动)if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}} else {//对象消失(向上滚动)if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}}});}).滚动();//在页面加载时调用滚动处理程序});

.fade {边距:50px;填充:50px;背景颜色:浅绿色;不透明度:1;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><div><div class="fade">淡入01</div><div class="fade">淡入02</div><div class="fade">淡入03</div><div class="fade">淡入04</div><div class="fade">淡入05</div><div class="fade">淡入06</div><div class="fade">淡入07</div><div class="fade">淡入08</div><div class="fade">淡入09</div><div class="fade">淡入 10</div>

(小提琴:http://jsfiddle.net/eLwex993/2/)

  • 我将淡入淡出代码行包裹在一个 if 子句中:if ($(this).css("opacity")==0) {...}.这确保对象仅在 opacity0 时淡入.淡出也一样.这可以防止淡入和淡出相互影响,因为现在在一个对象上只有两者中的一个同时运行.
  • 我将 .animate() 更改为 .fadeTo().它是 jQuery 的不透明度专用函数,编写起来要短得多,而且可能比动画更轻.
  • 我将 .position() 更改为 .offset().这总是相对于身体计算,而位置是相对于父级的.对于您的情况,我认为抵消是可行的方法.
  • 我将 $(window).height() 更改为 $(window).innerHeight().根据我的经验,后者更可靠.
  • 在滚动处理程序之后,我在页面加载时使用 $(window).scroll(); 调用该处理程序一次.现在,您可以为页面上所有需要的对象指定 .fade 类,并且在页面加载时不可见的对象将立即淡出.
  • 我从 HTML 和 CSS 中删除了 #container,因为(至少对于这个答案)它不是必需的.(我想也许你需要 height:2000px 因为你使用了 .position() 而不是 .offset(),否则我不需要知道.当然可以将它留在您的代码中.)
<小时>

更新

如果您想要01 以外的不透明度值,请使用以下代码:

$(window).on("load",function() {功能淡入淡出(页面加载){var windowBottom = $(window).scrollTop() + $(window).innerHeight();无功最小值 = 0.3;无功最大值 = 0.7;无功阈值 = 0.01;$(".fade").each(function() {/* 检查每个所需元素的位置 */var objectBottom = $(this).offset().top + $(this).outerHeight();/* 如果元素完全在窗口范围内,则将其淡入 */if (objectBottom < windowBottom) {//对象进入视图(向下滚动)if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}} else {//对象消失(向上滚动)if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}}});淡入淡出(真);//页面加载时淡入淡出元素$(window).scroll(function(){fade(false);});//淡出滚动元素});

.fade {边距:50px;填充:50px;背景颜色:浅绿色;不透明度:1;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><div><div class="fade">淡入01</div><div class="fade">淡入02</div><div class="fade">淡入03</div><div class="fade">淡入04</div><div class="fade">淡入05</div><div class="fade">淡入06</div><div class="fade">淡入07</div><div class="fade">淡入08</div><div class="fade">淡入09</div><div class="fade">淡入 10</div>

(小提琴:http://jsfiddle.net/eLwex993/3/)

  • 我在 if 子句中添加了一个阈值,请参阅下面的说明.
  • 我在函数开始时为 thresholdmin/max 创建了变量.在函数的其余部分,这些变量被引用.这样,如果您想再次更改这些值,只需在一个地方进行.
  • 我还添加了||pageLoad 到 if 子句.这对于确保所有对象在页面加载时淡化到正确的不透明度是必要的.pageLoad 是一个布尔值,在调用 fade() 时作为参数发送.
    我不得不将淡入淡出代码放在额外的 functionfade() {...} 中,以便能够沿着 pageLoad 布尔值发送滚动处理程序被调用.
    我没有看到任何其他方法可以做到这一点,如果有人这样做,请发表评论.

解释:
你的小提琴中的代码不起作用的原因是实际的不透明度值总是与您设置的值略有不同.因此,如果您将不透明度设置为 0.3,则实际值(在本例中)为 0.300000011920929.这只是您必须通过跟踪和错误学习的那些小错误之一.这就是这个 if 子句不起作用的原因:if ($(this).css("opacity") == 0.3) {...}.

我添加了一个阈值,以将这种差异考虑在内:== 0.3 变为 <= 0.31.
(我已经将阈值设置为0.01,当然可以更改,只要实际不透明度介于设置值和此阈值之间即可.)

运算符现在从 == 更改为 <=>=.

<小时>

更新 2:

如果您想根据元素的可见百分比淡化元素,请使用以下代码:

$(window).on("load",function() {功能淡入淡出(页面加载){var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();var min=0.3,max=0.7,阈值=0.01;$(".fade").each(function() {/* 检查每个所需元素的位置 */var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;/* 根据可见百分比淡入/淡出元素 */如果 (objectTop < windowTop) {if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}} else if (objectBottom > windowBottom) {if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}} else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}});淡入淡出(真);//页面加载时淡入淡出元素$(window).scroll(function(){fade(false);});//淡出滚动元素});

.fade {边距:50px;填充:50px;背景颜色:浅绿色;不透明度:1;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><div><div class="fade">淡入01</div><div class="fade">淡入02</div><div class="fade">淡入03</div><div class="fade">淡入04</div><div class="fade">淡入05</div><div class="fade">淡入06</div><div class="fade">淡入07</div><div class="fade">淡入08</div><div class="fade">淡入09</div><div class="fade">淡入 10</div>

(小提琴:http://jsfiddle.net/eLwex993/5/)

I'm trying to get a series of elements to fade in on scroll down when they are fully visible in the window. If I keep scrolling down, I do not want them to fade out, but if I scroll up, I do want them to fade out.

This is the closest jsfiddle I've found. http://jsfiddle.net/tcloninger/e5qaD/

$(document).ready(function() {

/* Every time the window is scrolled ... */
$(window).scroll( function(){

    /* Check the location of each desired element */
    $('.hideme').each( function(i){

        var bottom_of_object = $(this).position().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, fade it it */
        if( bottom_of_window > bottom_of_object ){

            $(this).animate({'opacity':'1'},500);

        }    
    }); 
}); 
});

It does exactly what I want on scroll down, but I also want the elements to fade out if I scroll up past them.

I tried this with no luck.

            if( bottom_of_window > bottom_of_object ){

                $(this).animate({'opacity':'1'},500);  

            } else {

               $(this).animate({'opacity':'0'},500); }

Thanks so much for taking the time to look at this.

解决方案

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

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

.fade {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div>
  <div class="fade">Fade In 01</div>
  <div class="fade">Fade In 02</div>
  <div class="fade">Fade In 03</div>
  <div class="fade">Fade In 04</div>
  <div class="fade">Fade In 05</div>
  <div class="fade">Fade In 06</div>
  <div class="fade">Fade In 07</div>
  <div class="fade">Fade In 08</div>
  <div class="fade">Fade In 09</div>
  <div class="fade">Fade In 10</div>
</div>

(fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

$(window).on("load",function() {
  function fade(pageLoad) {
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();
    var min = 0.3;
    var max = 0.7;
    var threshold = 0.01;
    
    $(".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")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}
      } else { //object goes out of view (scrolling up)
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}
      }
    });
  } fade(true); //fade elements on page-load
  $(window).scroll(function(){fade(false);}); //fade elements on scroll
});

.fade {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div>
  <div class="fade">Fade In 01</div>
  <div class="fade">Fade In 02</div>
  <div class="fade">Fade In 03</div>
  <div class="fade">Fade In 04</div>
  <div class="fade">Fade In 05</div>
  <div class="fade">Fade In 06</div>
  <div class="fade">Fade In 07</div>
  <div class="fade">Fade In 08</div>
  <div class="fade">Fade In 09</div>
  <div class="fade">Fade In 10</div>
</div>

(fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

$(window).on("load",function() {
  function fade(pageLoad) {
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();
    var min=0.3, max=0.7, threshold=0.01;
    
    $(".fade").each(function() {
      /* Check the location of each desired element */
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;
      
      /* Fade element in/out based on its visible percentage */
      if (objectTop < windowTop) {
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}
      } else if (objectBottom > windowBottom) {
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}
    });
  } fade(true); //fade elements on page-load
  $(window).scroll(function(){fade(false);}); //fade elements on scroll
});

.fade {
  margin: 50px;
  padding: 50px;
  background-color: lightgreen;
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div>
  <div class="fade">Fade In 01</div>
  <div class="fade">Fade In 02</div>
  <div class="fade">Fade In 03</div>
  <div class="fade">Fade In 04</div>
  <div class="fade">Fade In 05</div>
  <div class="fade">Fade In 06</div>
  <div class="fade">Fade In 07</div>
  <div class="fade">Fade In 08</div>
  <div class="fade">Fade In 09</div>
  <div class="fade">Fade In 10</div>
</div>

(fiddle: http://jsfiddle.net/eLwex993/5/)

这篇关于向下滚动时淡入,向上滚动时淡出 - 基于窗口中的元素位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆