简体   繁体   English

滚动时更改元素的不透明度

[英]On scroll change element opacity

I have made it almost work but there is an problem with how fast opacity changes and also problem when i scroll back up. 我已经使它几乎可以工作了,但是不透明性变化有多快还有一个问题,当我向上滚动时也有问题。

Jsfiddle http://jsfiddle.net/dp1b51fs/2/ jsfiddle http://jsfiddle.net/dp1b51fs/2/

  1. I did set it to 5000 >> $(".bgimage").animate({opacity: 0.4}, "5000"); 我确实将其设置为5000 >> $(".bgimage").animate({opacity: 0.4}, "5000"); But it seems to be the same speed like when i had it on 500. What am i doing wrong? 但是它的速度似乎和我使用500时的速度相同。我在做什么错? (have tried writing "5000ms" and "500s" but it's the same) (曾尝试编写“ 5000ms”和“ 500s”,但这是相同的)
  2. When i scroll down then the element (background image) fades out to 0.4 opacity. 当我向下滚动时,该元素(背景图像)会淡出至0.4不透明度。 But when i scroll back up then opacity just goes to 1 opacity and doesnt fades in or similar. 但是,当我向上滚动时,不透明度将变为1,并且不会消失或类似。

You need to run .stop() before the animation, or else you're just stopping the scrolling up animation you're trying to do: 您需要在动画之前运行.stop() ,否则就只是停止尝试尝试向上滚动的动画:

$(document).scroll(function () {
    if ($(this).scrollTop() > 500) {
      $(".bgimage").stop().animate({opacity: 0.4}, 500);
    } else {
      $(".bgimage").stop().animate({opacity: 1}, 500);
    }

});

JSFiddle 的jsfiddle


Edit: To clarify what I did you your code: Edit:要澄清我对您的代码做了什么:

I removed $(this).scrollTop() > 1 because if $(this).scrollTop() > 500 is true, then the other one is already true as well, so ultimately, there is no need for it. 我删除了$(this).scrollTop() > 1因为如果$(this).scrollTop() > 500为true,那么另一个也已经为true,因此最终不需要。

I wrapped your scrolled up animation in a else statement, because what you were origonally doing was firing whatever the user scrolled (even if they were more than 500), it just looked kinda messy and you were firing two functions at once. 我将滚动的动画包装在else语句中,因为您最初执行的操作是触发用户滚动的任何内容(即使它们大于500),看起来也很混乱,并且您一次要触发两个功能。

I also removed the return because I saw no used for it in your context. 我还删除了return因为在您的情况下,我认为没有用过。

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

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