好的,我有一些带有绝对定位和隐藏的子元素div.caption
的弹出式气泡效果。div.caption
有一个父元素a.logo
我想从a.logo
中减去div.caption
的高度,并将.css("top",..)
设置为该数字的一半。
。Logo = 200px(高度)div. title - 250px (height)
-((250 - 200)/2) = -25
结果应该是子元素相对于父元素的垂直居中(尽管它溢出了父元素)。
我有以下HTML
<a class="logo" href="#">
<div class="caption">Caption Text</div>
</a>
<a class="logo" href="#">
<div class="caption">Caption Text</div>
</a>
<a class="logo" href="#">
<div class="caption">Caption Text</div>
</a>
jQuery 和
$("div.caption").each(function() {
var theHeight = $(this).height();
var container = $('this').closest('a.logo').height();
if( theHeight > container ) {
$(this).css("top",-( (theHeight-container)/2 ) + "px");
}
});
真正让我困惑的是,$(this).closest('a.logo')
为height();
返回40px,但DOM报告的元素高度为200px。
我的目标变量是关闭的,但我需要使用.this()
,因为所有这些目标都有多个实例,我需要单独设置top属性
去掉this
周围的引号。您的代码目前正在寻找元素<this>
,并找到最接近的a.logo
,它不存在。height
设置为null
,在数字上下文中计算结果为零。
var container = $(this).closest('a.logo').height();