我有一个 DIV,我希望文本在该 div 中垂直居中。我不能使用固定的像素高度,只能使用百分比。
<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”的高度。
有什么建议吗?
最佳答案
试试这个:
$('.myText').each(function(index,element) {
var textHeight = $(element).height();
var vertAdj = ((imageHeight - textHeight) / 2);
$(element).css('top', vertAdj);
});
有关更多信息,请参阅.each
文档http://api.jquery.com/each/
关于jquery - 使用 jquery 设置 CSS Top 值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866305/