>我目前有一个父元素,它有绝对定位的子元素。这基本上破坏了父元素的高度,我想根据当前显示的子元素添加回高度(所有子元素都有不同的高度(。
<button id="one">One</button>
<button id="two">Two</button>
<button id="three">Three</button>
<div id="parent">
<div class="child">height of 250px</div>
<div class="child">height of 500px</div>
<div class="child">height of 750px</div>
</div>
我有JQuery来显示其中一个孩子,并在您按下其中一个按钮时添加一类"活动"。例如:当您按下按钮#one时,第一个子项将显示并被赋予"活动"类。我目前对身高的 JQuery 是:
var maxHeight = 0;
$('.child').each(function() {
if($(this).height() > maxHeight) {
maxHeight = $(this).height();
}
});
$('#parent').height(maxHeight);
这只会抓取并应用最高孩子的身高 (750px(,当我希望高度根据显示的孩子和/或具有"活动"类来动态时。
从你的描述中很难理解你的问题。我试图猜测它并创建一个片段。我希望它有所帮助!
var parent = $('#parent');
$('[data-target]').each(function() {
$(this).bind('click', function(){
var elID = $(this).data('target');
var elHeight = $('#'+elID).height();
parent.height(elHeight);
console.log(elID, elHeight)
})
});
#parent {
border: 3px solid red;
}
.child {
position: absolute;
width: 200px;
}
.child:nth-child(1) {height: 20px; background-color: steelblue;}
.child:nth-child(2) {height: 40px; background-color: wheat;}
.child:nth-child(3) {height: 60px; background-color: firebrick;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-target="one" >One</button>
<button data-target="two" >Two</button>
<button data-target="three" >Three</button>
<div id="parent">
<div class="child" id="one">height of 20px</div>
<div class="child" id="two">height of 40px</div>
<div class="child" id="three">height of 60px</div>
</div>