简体   繁体   中英

Hide Sticky Div Once Scrolling Past Next Parent Div

I'm trying to hide a "sticky" div once it scrolls past the next parent div. I've currently successfully have it so it appears after scrolling "y > 100" but I'm having a lot of trouble getting the "Sticky Note" to disappear after scrolling past #break.

Example below.

http://codepen.io/anon/pen/BojKBx

 $(document).scroll(function() { var y = $(this).scrollTop(); if (y > 100) { $('.bottomMenu').fadeIn(); } else { $('.bottomMenu').fadeOut(); } }); 
 .bottomMenu { display: none; position: fixed; bottom: 0; width: 50%; height: 60px; border-bottom: 1px solid #000; z-index: 1; margin: 0 auto; left: 50%; margin-left: -500px; text-align: center; } #header { font-size: 50px; text-align: center; height: 60px; width: 100%; background-color: red; } #container { height: 2500px; } #break { text-align: center; font-size: 30px; margin-bottom: 300px; width: 100%; background-color: yellow; } #footer { height: 60px; background-color: red; width: 100%; bottom: 0; } 
 <div id="header">Home</div> <div class="bottomMenu"> <h2>Sticky Note</h2> </div> <div id="container"></div> <div id="break">Should Not Be Seen After This Point</div> <div id="footer"></div> 

You can get Y position of a div (its vertical offset starting from the top of the page), and then add condition to show sticky note only when you're below the required "Y" coordinate, and above the required div. Example: http://codepen.io/anon/pen/EVPKyP

Javascript code:

$(document).scroll(function () {
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = document.getElementById("break").getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top - window.innerHeight;
    var y = $(this).scrollTop();
    if (y > 100 && y < offset) {
        $('.bottomMenu').fadeIn();
    } else {
        $('.bottomMenu').fadeOut();
    }

});

Sources:

Retrieve the position (X,Y) of an HTML element

screen width vs visible portion

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