简体   繁体   中英

increase div's opacity on scroll when div at the top of the page

I am trying to make a function which starts to increase (and immediately decrease after opacity equal 1) opacity of div on scroll at the specific place of the window, but my function works only with the first div. I mean second and third divs start changing their opacity at the same time with the first div. But they should do it only if they at the viewport. How to make it works with bottom divs properly?

 $(document).ready(function() { $(window).on('scroll', function() { var first = $('div.first') var second = $('div.second') var third = $('div.third') var op1 = opacityUp(first, 1, window.innerHeight, 1.5) var op2 = opacityUp(second, 1, 1.5, 1.5) var op3 = opacityUp(third, 1, 1.5, 1.5) }) }) function opacityUp(div, opacityLevel, topMargin, opacitySpeed) { // div position where to start increasing opacity const elPosition = (window.pageYOffset - window.innerHeight / topMargin); div.css({ opacity: function() { let val = 0 + (elPosition/(window.innerHeight*opacitySpeed)); console.log(elPosition) if (val <= opacityLevel) { return val } else { return opacityLevel } } }); }
 div { height: 100vh; opacity: 0; display: flex; align-items: center; justify-content: center; }.first { background: red; }.second { background: green; }.third { background: black; } <:-- begin snippet: js hide: false console: true babel: false -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <div class="first"></div> <div class="second"></div> <div class="third"></div>

I think the problem might have to do with the fact that elPosition doesn't take the actual element's position into account. If you want to define the position where the element begins to reduce opacity as the point at which the div enters the viewport, I'd change it to something like:

const elPosition = (window.pageYOffset - div.offset().top) + window.innerHeight;

Now, elPosition starts negative and reaches 0 when the div enters the viewport at the bottom. Then, elPosition increases by the number of pixels it travels up the screen (as the user scrolls down).

You can set the opacity by doing something like:

let val = (window.innerHeight - elPosition) / window.innerHeight;

if you want the opacity to fade to 0 and finish when the top of the element reaches the top of the viewport. You can add the div's height to the equation to start the opacity fading in the middle or bottom of the div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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