我如何去设置一个<div>在屏幕的中心使用jQuery?
当前回答
我将使用jQuery UI位置函数。
见工作演示。
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
如果我有一个id“test”的div居中,那么下面的脚本将在文档准备的窗口中居中div。(位置选项中“my”和“at”的默认值为“center”)
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
其他回答
我会推荐jQueryUI位置实用工具
$('your-selector').position({
of: $(window)
});
这给了你更多的可能性,而不仅仅是定心…
请使用这个:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
我在扩展@TonyL给出的精彩答案。我添加了Math.abs()来包装值,而且我还考虑到jQuery可能处于“无冲突”模式,例如在WordPress中。
I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.
我做的另一件事是通过缓存$(window)对象来加快速度,这样我就减少了额外的DOM遍历,并且我使用了集群CSS。
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
要使用,你可以这样做:
jQuery(document).ready(function($){
$('#myelem').center();
});
我想纠正一个问题。
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
以上代码在这种情况下将不起作用。height(假设用户调整屏幕大小,内容是动态的)和scrollTop() = 0,示例:
窗口。高度是600 这一点。高度是650
600 - 650 = -50
-50 / 2 = -25
现在方框在屏幕外的中心位置为-25。
你可以使用CSS translate属性:
position: absolute;
transform: translate(-50%, -50%);
阅读这篇文章了解更多细节。
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 音频停止功能
- 有Grunt生成index.html不同的设置
- 如何禁用谷歌翻译从HTML在Chrome
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格