jquery 中怎么让一个容器div显示在当前屏幕正中央,实现方法有很多种,本文章随便罗列几种方法。

 

第一种方法:jquery函数法

我喜欢给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;
}

只需要这样调用这个函数即可:

$(element).center();

 

第二种方法:jQueryUI定位工具

$(\'your-selector\').position({
    of: $(window)
});

例如:

<div id=\"test\" style=\"position:absolute;background-color:blue;color:white\">
    test div to center in window
</div>
<  type=\"text/ \">
$(function(){
  $(\"#test\").position({
     of: $(window)
  });
};
</ >

 

以上是关于jquery将一个DIV显示在屏幕中间(居中)的两种方法,希望对大家有所帮助。

收藏 打印