Change div css when user scrolls past it, using jQuery

后端 未结 3 1494
天涯浪人
天涯浪人 2020-12-16 07:54

When a user scrolls past a div I need it\'s css changed to position:fixed. Much like what is done here: http://imakewebthings.com/jquery-waypoints/shortcuts/sticky-elements/

相关标签:
3条回答
  • 2020-12-16 08:22

    I noticed in your answer #this disappears abruptly once you get down to #footer. I've tweaked your answer to allow for #this to stick to #footer and scroll which is a lot smoother.

    My demo uses slightly different markup and is a little more verbose so jump over to jsFiddle and check it out.

    Demo: jsfiddle.net/Marcel/e9hyw/

    0 讨论(0)
  • 2020-12-16 08:40

    This is what finally worked for me:

        jQuery(document).ready(function() {
        var topOfrel = jQuery("#this").offset().top;
        var topOffooter = jQuery("#footer").offset().top - jQuery(window).height(); 
        var topOffootero = topOffooter ;
        var boxheight = jQuery(window).height() - 130;//adjusting for position below
        jQuery(window).scroll(function() {
            var topOfWindow = jQuery(window).scrollTop();
            if (topOfrel < topOfWindow && topOffooter > topOfWindow) {
                jQuery("#this").css("position", "fixed").css("top", "130px").css("overflow","auto").css("height", boxheight + "px");
    
            } else {
                jQuery("#this").css("position", "static");
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-16 08:40

    the page you reference uses jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
    

    and also has other Javascript included on it that we don't see

    incidentally you can view it here:

    http://imakewebthings.com/jquery-waypoints/waypoints.js
    http://imakewebthings.com/jquery-waypoints/shortcuts/sticky-elements/waypoints-sticky.js
    

    the functions he uses can be seen there, but i would not say it's a quick answer. Based on his scripts he attaches a listener to the element after the page loads:

    <script type="text/javascript">
        $(document).ready(function() {
            $('.my-sticky-element').waypoint('sticky');
        });
    </script>
    

    If you have specific questions ask away, but i doubt many will go through explaining the entire script for you.

    0 讨论(0)
提交回复
热议问题