谁还没个明天 2008-10-17 00:11 采纳率: 50%
浏览 416
已采纳

使用 jQuery 在屏幕上居中显示一个 DIV

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

转载于:https://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen

  • 写回答

26条回答

  • 撒拉嘿哟木头 2014-01-26 11:04
    关注

    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;
    }
    

    Now we can just write:

    $(element).center();
    

    Demo: Fiddle (with added parameter)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(25条)

报告相同问题?

悬赏问题

  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?