码迷,mamicode.com
首页 > 其他好文 > 详细

设定div始终居中显示

时间:2015-03-17 12:34:36      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

<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>

设定div始终居中显示

标签:

原文地址:http://blog.csdn.net/colorsunlight/article/details/44338409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!