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:
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?
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.