Div that follows scroll (not position:fixed)

后端 未结 4 1820
迷失自我
迷失自我 2021-01-23 21:43

I found it sometime ago and now I can\'t. I want to find something like the shopping cart at the apple store, it\'s a div thats not positioned absolute nor fixed, for instance,

4条回答
  •  甜味超标
    2021-01-23 22:31

    The problem is with those divs that have height greater than the visible area height. So I wrote the script below.
    Put the sidebar id that you want and the id of the div that will stop the div following, like the footer. You will notice how useful this function is if the div has greater height than the window. I don't know why, but it works great only as inline javascript, not external.

    $(function () {
    var $sidebar = $("#sidebar"),
            $window = $(window),
            offset = $sidebar.offset(),
            topPadding = 5,
            $stopelement = $("#footer");
    
    var lastScrollTop = 0;
    
    $window.scroll(function () {
        if ($window.width() > 750) {
            if ($window.scrollTop() > lastScrollTop) {
                //down
                var addtotopposition = ($window.scrollTop() + $window.height()) - ($sidebar.height() + offset.top) + topPadding;
                if ($window.scrollTop() + $window.height() > offset.top + $sidebar.height()) {
                    if (offset.top + addtotopposition + $sidebar.height() < $stopelement.offset().top) {
                        $sidebar.stop().animate({
                            marginTop: addtotopposition
                        });
                    }
                } else {
                    $sidebar.stop().animate({
                        marginTop: 0
                    });
                }
            } else {
                //up
                var offset_top = offset.top + parseInt($sidebar.css("margin-top"));
                //console.log(offset_top + " + " + topPadding + ">" + $window.scrollTop());
                if (offset_top + topPadding > $window.scrollTop()) {
                    var addtotopposition = Math.max($window.scrollTop() - offset.top + topPadding, 0);
                    //console.logconsole.log(offset_top + "-" + addtotopposition + ">0");
                    if (offset_top - addtotopposition > 0) {
                        $sidebar.stop().animate({
                            marginTop: addtotopposition
                        });
                    } else {
                        $sidebar.stop().animate({
                            marginTop: 0
                        });
                    }
                }
            }
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
        lastScrollTop = $window.scrollTop();
    });
    

    });

提交回复
热议问题