简体   繁体   中英

How to make a div “stick” to the top of the page using jQuery?

I'm trying to make one of those things similar to the stackoverflow orange messages at the top, if you scroll down the page the message gets fixed to the top" and when you are scrolled back up for it to be in view it resumes being fixed and goes back to being displayed as block.

Anyway here is my attempt:

http://jsfiddle.net/cXP2y/

HTML:

<div style="border:1px solid red;height:50px;width:100%">Header</div>
<div id="message">Message</div>

<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

CSS:

#message { padding: 10px; background: #06c; }
.message-fixed { position: fixed; top: 0; width: 100%; }

jQUery:

$(function() {

var message = $('#message');
$(window).scroll(function() {
    if($(window).scrollTop() > (message.offset().top + message.height())) {
        message.addClass('message-fixed');
    }
    else {
        message.removeClass('message-fixed');
    }
});

});

As you can see it has that flicker happening. How can I prevent this?

Also is there a more optimized way to write my code?

There are a lot of questions about this lately...

See my answers here and here . Since you're using jQuery, it's very convenient - handle window 's scroll event, get the element's offset , clone it, and add or remove the appropriate class.

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