How to hover a Fixed element until it reaches some point

后端 未结 9 2256
栀梦
栀梦 2021-02-07 11:54

I\'ve got a div which I need to be fixed to the bottom of the screen, until it reaches some point after scrolling and stop there and stay. If a user start scrolling back up - ma

9条回答
  •  [愿得一人]
    2021-02-07 12:21

    $(window).scroll(function() {
        checkPosition('#myelement');
    });
    
    function checkPosition( element ){
    //choose your limit
    var positionLimit = 416;
    var y = getOffsetY();
    
    if( y <= positionLimit ){
        $(element).css({'position':'fixed','bottom':'0'});
    }
    else{
        $(element).css({'position':'relative'});
    }
    }
    

    //for browser compatibility

    function getOffsetY(){
    
    var  scrOfY = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
        } else if( document.body && ( document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
        } else if( document.documentElement && (  document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
        }
    
    return scrOfY;
    }
    

    This should be work. To get y offset of the element you'd have to use a function in order to have browser compatibility. All you have to do is set the correct limit position.

提交回复
热议问题