文章标题

本文介绍了一个使用jQuery实现的DIV居中显示的方法。该方法能够使指定的DIV元素无论在窗口大小变化时都能保持水平和垂直居中,并考虑了滚动条的影响。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="../jquery/jquery-1.9.1.min.js"></script>
<script> 
$(document).ready(function(){
    $('#centerDiv').center();
    $(window).on('resize',function(){
        $('#centerDiv').center({transition:50});
    });
});
(function($){
    $.fn.extend({
        center:function(options){
            var options=$.extend({ // Default values
                inside:window, // element, center into window
                transition:0, // millisecond, transition time
                minX:0, // pixel, minimum left element value
                minY:0, // pixel, minimum top element value
                withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                vertical:true, // booleen, center vertical
                horizontal:true // booleen, center horizontal
            }, options);
            return this.each(function(){
                var props={position:'absolute'};
                if(options.vertical){
                    var top=($(options.inside).height()-$(this).outerHeight())/2;
                    if(options.withScrolling) top+=$(options.inside).scrollTop()||0;
                    top=(top>options.minY?top:options.minY);
                    $.extend(props,{top:top+'px'});
                }
                if(options.horizontal){
                    var left=($(options.inside).width()-$(this).outerWidth())/2;
                    if (options.withScrolling) left+=$(options.inside).scrollLeft()||0;
                    left=(left>options.minX?left:options.minX);
                    $.extend(props,{left:left+'px'});
                }
                if(options.transition>0) $(this).animate(props,options.transition);
                else $(this).css(props);
                return $(this);
            });
        }
    });
})(jQuery);
</script>
<style type="text/css">
#centerDiv {
    width:550px;
    height:550px;
    font-size:12px;
    color:blue;
    background-color:#808080;
}
</style>
<title></title>
</head>
<body>
<div id="centerDiv">设定div始终居中显示</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值