2012-05-17 55 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