您的位置:首页 > 其它

设定div始终居中显示

2015-03-17 10:28 211 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: