根据高度滚动时更改不透明度

时间:2022-06-17 19:56:37

I have multiple sections on a page. Each has an overlay that starts out at 1 opacity. I would like it to reduce opacity as you scroll with it reaching 0 when the bottom of the element is at the top of the page.

我在页面上有多个部分。每个都有一个以1不透明度开始的叠加层。当元素的底部位于页面顶部时,我希望它在滚动时降低不透明度,达到0。

I based this code on another question here, and it almost works for one, but I want to do this for multiple elements on the page and that's where things break down. When I try it, each subsequent element starts out less opaque and it's even worse if the window size is reduced.

我将此代码基于另一个问题,它几乎适用于一个,但我想对页面上的多个元素执行此操作,这就是事情发生的地方。当我尝试它时,每个后续元素开始时不那么不透明,如果窗口大小减小则更糟。

$(window).scroll(function () {
    var homeTop = $(window).scrollTop();
    var height = $(window).height() / 2;

    $('#splashback-home').css({
        'opacity': ((height - homeTop) / height)
    });
});

How can I make this dynamic for say any element with the .splashback class?

如何使用.splashback类表示任何元素?

I'm thinking something like this?

我在想这样的事情?

    $('.splashback').each(function () {
        var scrollTop = $(window).scrollTop();
        var thisTop = $(this).offset().top;
        var thisHeight = $(this).height();
        newOpacity = ???
        if (newOpacity > 1) newOpacity = 1;
        $(this).css({'opacity': newOpacity});
    });

1 个解决方案

#1


4  

You're close - you need to take the element's offset into account for each .splashback:

你很接近 - 你需要为每个.splashback考虑元素的偏移量:

$(window).scroll(function() {
  var homeTop = $(window).scrollTop();

  $(".splashback").each(function() {
    var height = $(this).height();
    var offset = $(this).offset().top;
    var opacity = (height - homeTop + offset) / height;

    $(this).css("opacity", opacity);
  });
});
div {
  background: red;
  height: 1000px;
  margin-bottom: 100px;
}

.splashback {
  background: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Some div (will not fade)</div>
<div class="splashback">Some div splashback 1</div>
<div class="splashback">Some div splashback 2</div>
<div>Some div (will not fade)</div>

#1


4  

You're close - you need to take the element's offset into account for each .splashback:

你很接近 - 你需要为每个.splashback考虑元素的偏移量:

$(window).scroll(function() {
  var homeTop = $(window).scrollTop();

  $(".splashback").each(function() {
    var height = $(this).height();
    var offset = $(this).offset().top;
    var opacity = (height - homeTop + offset) / height;

    $(this).css("opacity", opacity);
  });
});
div {
  background: red;
  height: 1000px;
  margin-bottom: 100px;
}

.splashback {
  background: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Some div (will not fade)</div>
<div class="splashback">Some div splashback 1</div>
<div class="splashback">Some div splashback 2</div>
<div>Some div (will not fade)</div>