我的 jQuery 有问题:我使用的脚本允许我通过给元素一个类来居中元素,但这个脚本没有采用正确的高度。
这是我的 HTML 代码:
<div class="logoutscreen blackbackground">
<div class="window centered" style="display: block;">
[CONTENT HERE]
</div>
</div>
这是我的 jQuery 代码:
$(function () {
$(".centered").css({
'position': 'absolute',
'left': '50%',
'top': '50%',
'margin-left': -$(this).outerWidth() / 2,
'margin-top': -$(this).outerHeight() / 2
});
});
问题是脚本不使用 .centered 类 (.window) 的 div 的高度和宽度,而是他的父类 (.logoutscreen) 的高度和宽度。
为什么会这样? :(
最佳答案
$(this)
的使用是您的问题。与其他方法不同,您不能在 jQuery 的 .css()
方法中将 this
父对象作为 $('.centered')
访问...它将默认为全局 window
对象。
您要做的是缓存您的对象并显式引用它:
var $centered = $('.centered');
$centered.css({
position:'absolute',
left:'50%',
top:'50%',
marginLeft:((-1 * $centered.outerWidth()) / 2),
marginTop:((-1 * $centered.outerHeight()) / 2)
});
这应该能为您提供所需的信息。但是,如果您有多个实例,则需要执行以下操作:
$centered.each(function(){
var $self = $(this);
$self.css({
position:'absolute',
left:'50%',
top:'50%',
marginLeft:((-1 * $self.outerWidth()) / 2),
marginTop:((-1 * $self.outerHeight()) / 2)
});
});
这样每个独特的 height
和 width
都得到尊重。
关于javascript - jQuery 没有采用正确的 div 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465834/