您可以像这样使其居中:
$('#elementID').css({
position:'absolute',
top:'50%',
left:'50%',
width:'600px', // adjust width
height:'300px', // adjust height
zIndex:1000,
marginTop:'-150px' // half of height
marginLeft:'-300px' // half of width
});
请注意,元素将出现在中心,但滚动它不会移动。如果要让它出现在中心,则需要将position 设置为fixed。但是,这在 IE6 中不起作用。所以决定权在你:)
您还可以创建快速简单的 jQuery 插件:
(function($){
$.fn.centerIt = function(settings){
var opts = $.extend({}, $.fn.centerIt.defaults, settings);
return this.each(function(settings){
var options = $.extend({}, opts, $(this).data());
var $this = $(this);
$this.css({
position:options.position,
top:'50%',
left:'50%',
width:options.width, // adjust width
height:options.height, // adjust height
zIndex:1000,
marginTop:parseInt((options.height / 2), 10) + 'px' // half of height
marginLeft:parseInt((options.width / 2), 10) + 'px' // half of height
});
});
}
// plugin defaults - added as a property on our plugin function
$.fn.centerIt.defaults = {
width: '600px',
height: '600px',
position:'absolute'
}
})(jQuery);
然后像这样使用它:
$('#elementId').centerIt({width:'400px', height:'200px'});
要在调整窗口大小时使其居中,您可以使用resize 事件以防它无法像这样居中:
$(window).resize(function(){
$('#elementId').centerIt({width:'400px', height:'200px'});
});