1
我有一个DIV,我希望文本在该div内垂直居中。我不能使用固定的像素高度,只有百分比。使用jquery设置CSS Top值不起作用
<div style="position:relative; width: 100%; height: 100%;">
<img src="images/thumb-member-placeholder.gif" alt="" class="myImage" />
<div class="myText" style="display: inline-block; position: absolute; z-index:500; text-align:center;">Image Text</div>
</div>
我有100个这样的div,其中“myText”可以是1行或3行。
所以我使用jQuery来检测的高度并设置相应TOP值:
$(window).load(function() {
var imageHeight = $('.myImage').height();
$('.myText').each(function() {
var textHeight = $('.myText').height();
var vertAdj = ((imageHeight - textHeight)/2);
$(this).css('top', vertAdj);
});
});
但它无法正常工作。它始终输出相同的TOP值,而当文本变为2或3行时,不会检测“myText”的高度。
有什么建议吗?
'变种textHeight不同= $( '会将myText。')的高度();'获得的第一个元素的值。堆栈,为什么它都是一样的。 –
我的建议是避免使用jquery,只能使用CSS垂直居中。 – DaniP
谢谢卡尔!那么我该如何修改我的JavaScript,以便通过div循环,并将TOP值分别设置为每个div? – user3019107