gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:54:40 26 4
gpt4 key购买 nike

我该如何设置 <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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com