设定div始终居中显示

<script type="text/javascript">
(function($){
    $.fn.extend({
        center:function(options){        //center插件
            var options=$.extend({       //默认属性值
                inside:window,           //元素居于窗体中心
                transition:0,            //元素居中移动时的时间,单位是millisecond
                minX:0,                  //元素最小X方向距边值
                minY:0,                  //元素最小Y方向距边值
                withScrolling:true,      //是否支持滚动条
                vertical:true,           //是否支持垂直居中
                horizontal:true          //是否支持水平居中
            },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).outerHeight())/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>
<script type="text/javascript">
$(document).ready(function(){
    $("#centerDiv").center();
    $(window).bind('resize',function(){
        $("#centerDiv").center({transition:500});
    });
});
</script>
</head>
<body>
    <div id="centerDiv" style="height: 100px;width: 200px;background: #ccf">设定div始终居中显示</div>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值