How can I make a div stick to the top of the screen once it's been scrolled to?

后端 未结 21 1701
Happy的楠姐
Happy的楠姐 2020-11-22 07:12

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place

21条回答
  •  [愿得一人]
    2020-11-22 07:48

    I have links setup in a div so it is a vertical list of letter and number links.

    #links {
        float:left;
        font-size:9pt;
        margin-left:0.5em;
        margin-right:1em;
        position:fixed;
        text-align:center;
        width:0.8em;
    }
    

    I then setup this handy jQuery function to save the loaded position and then change the position to fixed when scrolling beyond that position.

    NOTE: this only works if the links are visible on page load!!

    var listposition=false;
    jQuery(function(){
         try{
            ///// stick the list links to top of page when scrolling
            listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
            console.log(listposition);
            $(window).scroll(function(e){
                $top = $(this).scrollTop();
                $el = jQuery('#links');
                //if(typeof(console)!='undefined'){
                //    console.log(listposition.top,$top);
                //}
                if ($top > listposition.top && $el.css('position') != 'fixed'){
                    $el.css({'position': 'fixed', 'top': '0px'});
                }
                else if ($top < listposition.top && $el.css('position') == 'fixed'){
                    $el.css({'position': 'static'});
                }
            });
    
        } catch(e) {
            alert('Please vendor admin@mydomain.com (Myvendor JavaScript Issue)');
        }
    });
    

提交回复
热议问题