2012-05-17 58 views
2

我有一個div需要被垂直居中在屏幕頁面滾動股利需要滾動頁面後,屏幕的垂直中心

這裏後是一個演示 - http://jsfiddle.net/JtZ7F/

<div style="height:1000px; border:1px solid red;"> 
    scroll 
    <span style="height:150px; width:100px; float:right; border:1px solid green; display:block; position:fixed;top:50%; margin-top:-75px;"> 
     need vertical center of the screen after page scroling 
    </span> 
</div> 

現在我使用position:fixed; ,這不是一個解決方案

我想停止頁面滾動時,我的綠色框順利地移動到屏幕的垂直中心。

我該如何在jQuery中做到這一點?

+0

,你能否告訴jQuery的工作,你已經完成的工作? –

+1

爲什麼'position:fixed'不是您的解決方案? –

+0

@Liam Spencer - 其實我不是jQuery專家。你有沒有簡單的腳本? – ShibinRagh

回答

3

在你的jQuery添加此功能:

jQuery.fn.center = function() { 
this.css("top", (($(window).height() - this.outerHeight())/2) + $(window).scrollTop() + "px");  
this.css("left", (($(window).width() - this.outerWidth())/2) + $(window).scrollLeft() + "px");  return this; } 

添加ID到您的跨越「測試」,並在的document.ready

$(document).ready(function(){  
$('#test').center(); 
}); 
+0

嘿,你測試了嗎?不在這裏工作 – ShibinRagh

+1

這裏是小提琴http://jsfiddle.net/rutwik/Xn88W/ – TRR

+0

感謝您的幫助,但我很抱歉地說,現在當我們頁面滾動綠色框仍然固定,不,這不是一個解決方案,我想當我們停止頁面滾動,然後綠色框移動到頁面的垂直中心,清除? – ShibinRagh

3

編寫下面這裏是我如何做到這一點,在測試Chrome & IE7 +,例如參見jsfiddle

$.fn.center = function() { 
        return this.css({ 
         'left': ($(window).width()/2) - $(this).width()/2, 
         'top': ($(window).height()/2) - $(this).height()/2, 
         'position': 'fixed' 
        }); 
       }; 

用法:

$(document).ready(function(){ 
    $(element).center(); 
}); 
+0

jsfiddle – ShibinRagh