javascript - 使用 jQuery 使 DIV 在屏幕上居中

标签 javascript jquery html css layout

我该如何设置 <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();

演示:Fiddle (添加参数)

关于javascript - 使用 jQuery 使 DIV 在屏幕上居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43539584/

相关文章:

javascript - 从右到左切换 Div

javascript - 根据窗口宽度更改javascript

javascript - 使用 Jquery 访问 innerhtml

javascript - 更改 Bootstrap Typeahead 的外观

javascript - 使用纯 javascript 或 jQuery 写入日志文件

javascript - 如何处理单击和选项卡中的焦点?

Javascript 幻灯片卡住

javascript - 通过 Bacon.js 使用多个事件流值

jquery - 我可以将类应用于包含链接的表行,而不是链接本身吗?

jquery - 为我的网站存储暗模式偏好