Start and stop div scrolling between two other divs

后端 未结 1 2000
心在旅途
心在旅途 2021-02-06 19:39

Someone else recently helped me out with the start of this question but I\'m after a little more help. I currently have this working -

var windw = this;

$.fn.f         


        
相关标签:
1条回答
  • 2021-02-06 19:50

    Add another parameter to your function to pass the start element, then set some vars inside your function to store its offset().top + height() as the start position, then just add another if to check if the scrollTop() value is lower than the start one, like this:

    var windw = this;
    
    $.fn.followTo = function (from, bumper) { //renamed "elem" to "bumper", to 
        var $this = this,                     //prevent ambiguity
            $window = $(windw),
            $from = $(from),
            $bumper = $(bumper),
            $startPos = $from.offset().top + $from.height(), //new start position
            bumperPos = $bumper.offset().top,
            thisHeight = $this.outerHeight(),
            setPosition = function(){
                if ($window.scrollTop() < $startPos) { //new if < startPos
                    $this.css({
                        position: 'absolute',
                        top: $startPos //resets element to start position
                    });
                } else if ($window.scrollTop() > (bumperPos - thisHeight)) {
                    $this.css({
                        position: 'absolute',
                        top: (bumperPos - thisHeight)
                    });
                } else {
                    $this.css({
                        position: 'fixed',
                        top: 0
                    });
                }
            };
        $window.resize(function()
        {
            bumperPos = pos.offset().top;
            thisHeight = $this.outerHeight();
            setPosition();
        });
        $window.scroll(setPosition);
        setPosition();
    };
    
    $('#one').followTo('#half', '#two');
    

    JSFiddle

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