所以我试图使用以下代码使用jQuery在窗口中居中div:
(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);
这在Chrome中运行良好但它似乎没有垂直居中在Firefox中,我无法弄清楚我做错了什么。 firefox是否存在使其无法计算窗口高度的错误?
答案 0 :(得分:0)
试试这个:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
用法:
$(element).center();
答案 1 :(得分:0)
我不记得我改变了什么,但现在是:
$.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);
$(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);
}
});
似乎在firefox中运行良好:http://jsfiddle.net/NQRUF/4/