3

我有一个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 中做到这一点?

4

2 回答 2

4

在您的 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(); 
});
于 2012-05-17T10:13:47.783 回答
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();
});
于 2013-05-15T14:09:29.987 回答