2011-08-26 83 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(); 
相關問題