我有一系列的div有一個'right'類。在這些div中我有內聯圖像。我需要編寫一個函數,根據其父容器'a.heading'的高度在div內垂直對齊圖像。圖像和父容器具有未知高度。 我有這個迄今爲止工作,但它只適用於圖像的第一個實例。請你能告訴我如何編寫一個函數遍歷所有的圖像和div。每個函數jquery
//calculate height of parent container
var parent_height = $('a.heading').height();
//get the height of the image
var image_height = $('.right img.accreditation').height();
//calculate how far from top the image should be
var top_margin = (parent_height - image_height)/2;
// set the right div to be the same height as the parent height
$('.right').css('height', parent_height);
//and change the margin-top css attribute of the image
$('.right img.accreditation').css('margin-top' , top_margin);
下面是HTML:
<div class="course-list accounting" id="left-accordion">
<div class="panel-group accordion">
<div class="panel panel-default">
<div class="panel-heading"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseCourseOne" class="heading">
<h4 class="panel-title">
<div class="left hidden-xs"> <span class="title"> <b>AAT</b> (Association of Accounting Technicians) </span> </div>
<div class="right"> <img src="img/logo-aat-white.png" alt="AAT" class="accreditation" width="63" height="36" > <span class="count visible-xs">6</span> </div>
</h4>
</a> </div>
<div id="collapseCourseOne" class="panel-collapse collapse in">
<div class="panel-body">
<ul>
<li><a href=""><span>AAT Access</span></a></li>
<li><a href=""><span>AAT Level 2 Certificate in Accounting</span></a></li>
<li><a href=""><span>AAT Level 3 Diploma in Accounting</span></a></li>
<li><a href=""><span>AAT Level 2 Certificate & Level 3 Diploma in Accounting</span></a></li>
<li><a href=""><span>AAT Level 4 Diploma in Accounting</span></a></li>
<li><a href=""><span>AAT Level 3 & 4 Diplomas in Accounting</span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="course-list accounting" id="right-accordion">
<div class="panel-group accordion">
<div class="panel panel-default">
<div class="panel-heading"> <a data-toggle="collapse" data-parent="#accordion" href="#collapseCourseTwo" class="heading">
<h4 class="panel-title">
<div class="left hidden-xs"> <span class="title"> <b>ACCA</b> (Association of Chartered Certified Accountants) </span> </div>
<div class="right"> <img src="img/logo-acca-white.png" alt="ACCA" class="accreditation" > <span class="count visible-xs">1</span> </div>
</h4>
</a> </div>
<div id="collapseCourseTwo" class="panel-collapse collapse in">
<div class="panel-body">
<ul>
<li><a href=""><span>ACCA Level 4 Diploma</span></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
感謝lfarroco,但它計算父div高度爲null? – madameFerry
我看了你的HTML,更新了答案 – lfarroco
現在你需要找到一個合適的父元素來引用,試着給你的h4設置一個css高度,然後把h4作爲父元素 – lfarroco