jquery将一个DIV显示在屏幕中间(居中)

时间:2017-11-06
div垂直居中是网站前端开发经常出现的需求之一,一般解决这类垂直居中的问题,我们都是使用css,但是有时候我们不得不使用js来实现,本文章向大家介绍jquery实现div在屏幕上左右居中和垂直居中,需要的朋友可以参考一下。

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>
<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>

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