当用户向下滚动页面时,增加元素的不透明度 [英] Increase element opacity when user scrolls down the page

查看:68
本文介绍了当用户向下滚动页面时,增加元素的不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多与用户滚动时修改元素不透明度有关的问题,但是还没有找到一个可以帮助我实现所需方式的问题.我尝试了几种公式,但未能达到我想要的效果.

I've seen a lot of question related to modifying an element opacity when user scrolls but haven't found one that helps me the way I need. I have tried several formulas and haven't been able to achieve the effect I want.

我有一个带有BG图像的标题,并且在其中有一个div作为覆盖,我希望它在用户向下滚动时变得越来越暗(不透明度增加).

I have a header with a BG image, and inside it a div that I use as an overlay, and I want it to get darker and darker smoothly (opacity increase) while the user scrolls down.

理想的效果是:

在CSS中,不透明度默认设置为0.2.当用户开始向下滚动时,它将开始从0.2增大到1.当用户再次向上滚动时,它将从1(或原来的值)减小到0.2.

Opacity is by default set to 0.2 in CSS. When user starts scrolling down it will start increasing from 0.2 to 1. When user scrolls up again it will decrease from 1 (or whatever value it was) to 0.2.

提琴: https://jsfiddle.net/z7q2qtc6/

<div class='nice-header'>
  <div class='header-overlay'></div>
</div>

CSS

.nice-header {
  position: relative;
  height: 300px;
  background: center center;
  background-size: cover;
  background-image: url(http://www.boeing.com/resources/boeingdotcom/commercial/787/assets/images/marquee-787.jpg);
}

.header-overlay {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background: rgb(0,0,0);
  opacity: 0.2;
}

JS

$(window).scroll(function() {
  $('.header-overlay').css({
    opacity: function() {
      var opacity = 0;
      //TODO:
      //Set opacity to a higer value whilst user scrolls
      return opacity;
    }
  });
});

推荐答案

您可以使用 .scrollTop()方法.

You can retrieve the current scrolling position by using the .scrollTop() method.

要计算不透明度,请从元素的高度中减去scrollTop值,然后将其除以元素的高度.

To calculate the opacity, subtract the scrollTop value from the height of the element and then divide that by the element's height.

此处的示例

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

  $('.header-overlay').css({
    opacity: function() {
      var elementHeight = $(this).height();
      return 1 - (elementHeight - scrollTop) / elementHeight;
    }
  });
});

如果要考虑元素的初始不透明度0.2:

If you want to account for the element's initial opacity of 0.2:

更新示例

$('.header-overlay').css({
  opacity: function() {
    var elementHeight = $(this).height(),
        opacity = ((1 - (elementHeight - scrollTop) / elementHeight) * 0.8) + 0.2;

    return opacity;
  }
});

这篇关于当用户向下滚动页面时,增加元素的不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆