简体   繁体   中英

make a div element stick to the top of the screen

I have wrote a script to detect when I reach the div element which is a navigation bar and then I change it's css to position fixed and top 0 so it will be fixed to the top, the problem that it doesn't do that, it acts like scroll to top and it jumps to the beginning of the screen. (it's flickers)

Javascript

        var currentScrollTop = 0;
        var barMenuOriginalTopPos = $('#navigation').offset().top;
        console.log('original:' + barMenuOriginalTopPos);
        $(window).scroll(function() {

            currentScrollTop = $(window).scrollTop();
            console.log(currentScrollTop);
            if(currentScrollTop >= barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') == false){
                $('#navigation').addClass('fixElementToTop');
            }
            else if(currentScrollTop < barMenuOriginalTopPos && $('#navigation').hasClass('fixElementToTop') ){
                $('#navigation').removeClass('fixElementToTop');
            }
        });

CSS

.fixElementToTop { position: fixed; top:0; z-index:100;}

Why

Here an non flickering solution via a jQuery plugin:

$(document).ready(function() {
    $('#fixedElement').scrollToFixed({ marginTop: 0 });
});

Live example : http://bigspotteddog.github.com/ScrollToFixed/
Plugin's website : https://github.com/bigspotteddog/ScrollToFixed/

a css fixed bar on top of the screen

<div style="position:fixed;top:10px;left:10px">Nav bar</div>

Review:

sorry i didn't understand your initial question, here it goes, to avoid it flicking you should start the object with a fixed position, lets say:

<div style="height:120px">XXX</div>
<div id="navigation" style="position: fixed; top:120; z-index:100;">Navigation</div>
<div class="win" style="border: 1px solid; height: 900px;"></div>

the code:

$(window).scroll(function() {
    currentScrollTop = 120-$(window).scrollTop();
    console.log(currentScrollTop);
    if (currentScrollTop<0) currentScrollTop=0
    $("#navigation")[0].style.top=currentScrollTop+"px";
});​

Set this line

var barMenuOriginalTopPos = $('#navigation').offset().top;

as

var barMenuOriginalTopPos = $('#navigation').offset().top + 6;

Refer LIVE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM