I like adding functions to jQuery so this function would help:
(我喜欢向jQuery添加功能,因此此功能将有所帮助:)
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;
}
Now we can just write:
(现在我们可以这样写:)
$(element).center();
Demo: Fiddle (with added parameter)
(演示: 小提琴 (带有添加的参数))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…