<!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>
文章标题
最新推荐文章于 2024-04-22 16:59:44 发布
本文介绍了一个使用jQuery实现的DIV居中显示的方法。该方法能够使指定的DIV元素无论在窗口大小变化时都能保持水平和垂直居中,并考虑了滚动条的影响。

2029

被折叠的 条评论
为什么被折叠?



