使用 jQuery 使 DIV 在屏幕上居中

Using jQuery to center a DIV on the screen(使用 jQuery 使 DIV 在屏幕上居中)

本文介绍了使用 jQuery 使 DIV 在屏幕上居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jQuery 在屏幕中央设置 <div>?

How do I go about setting a <div> in the center of the screen using jQuery?

推荐答案

我喜欢给 jQuery 添加函数,所以这个函数会有所帮助:

I like adding functions to jQuery so this function would help:

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();

演示:Fiddle(添加参数)

这篇关于使用 jQuery 使 DIV 在屏幕上居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 jQuery 使 DIV 在屏幕上居中

基础教程推荐