jQuery:将顶部位置设置为所包含子元素与父元素之间差异的 1/2
好的,我有一些弹出气泡效果,其中包含绝对定位和隐藏的子元素,称为 div.caption
。 div.caption
有一个名为 a.logo
的父元素。
我想从 a.logo
中减去 div.caption
的高度,并将 .css("top",..)
设置为 HALF那个数字。
例如:
a.logo = 200px(高度) div.caption - 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')
返回 40px height();
但 DOM 报告元素高度为 200px。
不知何故,我对变量的定位已关闭,但我需要使用 .this()
因为有多个。所有这些目标的实例,我需要单独设置顶部属性。
Ok, so I have some popup bubble effects with absolutely positioned and hidden child elements called div.caption
. div.caption
has a parent element named a.logo
.
I want to subtract the height of div.caption
from a.logo
and set.css("top",..)
to be HALF of that number.
For example:
a.logo = 200px (height)
div.caption - 250px (height)
-( (250 - 200)/2 ) = -25
The result should be vertical centering of the child in relation to the parent (despite the fact that it overflows the parent.
I have the following 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>
and 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");
}
});
What's really baffling me is that $(this).closest('a.logo')
is returning 40px for height();
but the DOM reports 200px for the elements height.
Somehow my targeting for the variables is off, but I need to use .this()
since there are multiple instances of all of these targets and I need to set the top property individually.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除
this
周围的引号。您的代码当前正在查找元素
,并查找最接近的a.logo
,但该元素不存在。height
设置为null
,在数字上下文中计算为零。Remove the quotes around
this
. Your code is currently looking for an element<this>
, and finding the closesta.logo
, which does not exist.height
is set tonull
, which evaluates to zero in a numeric context.