2011-08-26 39 views

回答

6

为什么不把它标记为position: fixed并将其保留在那里,无论用户在哪里滚动?那么你不需要任何形式的JavaScript欺骗。

然而,要回答你目前的问题,看来你提供定心一次,你你从来没有到窗口的滚动事件作出反应:

$(window).scroll(function() { $('#box').center(); }); 
7

你不需要为jQuery的,只是使用CSS

HTML

<div id="senad">content</div> 

CSS

#senad { width: 200px; height: 200px; position: fixed; top: 50%; left: 50%; border: 1px solid gray;} 

这样会保持元素居中。

+1

感谢,但我不能只使用CSS,因为div的高度并不总是相同的,因此,如果高度越多,股利的一半仍然隐藏。 – billa

+0

我想你正在使用CSS设置高度 - 那么为什么不同时设置'position:fixed'? – LeeGee

1

你在这里。更新了的document.body.scrollTop的滚动事件,并考虑

http://jsfiddle.net/8Dupa/4/

$(窗口).scroll(函数(){$( '#箱')中心();});

and within center()

top + = document.body.scrollTop;

1

使用这个插件:

jQuery.fn.center = function(){ 
this.css("position","absolute"); 
this.css("top","50%"); 
this.css("left","50%"); 
this.css("margin-top","-"+(this.height()/2)+"px"); 
this.css("margin-left","-"+(this.width()/2)+"px"); 
return this;} 

$("#id").center(); 
相关问题