简体   繁体   English

如何使用jQuery将div“粘贴”到页面顶部?

[英]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. 我正在尝试使其中之一类似于顶部的stackoverflow橙色消息,如果您向下滚动页面,则消息将固定在顶部”,并且当您向上滚动以使其在视图中时,它将恢复为固定,并返回显示为块。

Anyway here is my attempt: 无论如何,这是我的尝试:

http://jsfiddle.net/cXP2y/ http://jsfiddle.net/cXP2y/

HTML: 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: CSS:

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

jQUery: 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. 由于您使用的是jQuery,因此非常方便-处理windowscroll事件,获取元素的offset ,对其进行克隆,然后添加或删除适当的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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