我不能使用jQuery脚本来居中我的div

时间:2011-10-31 00:15:51

标签: javascript jquery css

我使用这个jQuery脚本根据浏览器窗口分辨率来居中我的div。但是我无法让它发挥作用。我在这里缺少什么?

我在jsFiddle中发布了它,以便更好地理解http://jsfiddle.net/9wvt3/

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}
$(#main).center();

2 个答案:

答案 0 :(得分:5)

这:

$(#main).center(); 

应该是:

$('#main').center();

请注意'函数参数中的$()

答案 1 :(得分:3)

您只是错过了#main

$('#main').center();上的引号

http://jsfiddle.net/9wvt3/2/