gpt4 book ai didi

jquery - 根据子元素的变化增加或减少父 div 高度

转载 作者:太空宇宙 更新时间:2023-11-04 01:43:49 25 4
gpt4 key购买 nike

https://jsfiddle.net/9b90twgf/15/

 $("#add").on("click",function(){
var top = parseInt($("#parentDiv .childDiv:last").css("top").split("px")[0])+90;

$("#parentDiv").append("<div class='childDiv' style='position:absolute; top:"+top+"px;'>divvvvvv</div>");
});

$("#remove").on("click",function(){
$("#parentDiv .childDiv:last").remove();
});
  #parentDiv
{
background: antiquewhite;
}
.childDiv
{
background: yellow;
width: 700px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="add">add</button><button id="remove">remove</button>
<div style="position: absolute; width: 700px; height: 210px;" id="parentDiv">
<div class="childDiv" style="position: absolute;">
Div one
</div>

<div class="childDiv" style="position: absolute; top: 75px;">
div two
</div>
<div class="childDiv" style="position: absolute; top: 140px;">
div three
</div>
</div>

我有一个父 div,在此之下我将附加和删除 HTML 元素作为子元素,如果我删除子元素,父 div 必须自动缩小其高度,如果我添加它必须自动扩展,我的要求是父元素和子项必须有绝对位置(style="position:absolute")

最佳答案

$("#add").on("click", function() {
addChild();
calculateParentHeight();
});

$("#remove").on("click", function() {
$(".parent .child:last").remove();
calculateParentHeight();
});

function calculateParentHeight() {
var height = 0;

$('.parent .child').each(function() {
height = height + $(this).height();
});

$('.parent').css('height', height + 20 + 'px');
}

calculateParentHeight();

function addChild() {
var top = 0;

$('.parent .child').each(function() {
top = top + $(this).height();
});

$(".parent").append("<div class='child' style='top:" + top + "px;'>divvvvvv</div>");
}
* {
box-sizing: border-box;
}

.parent {
position: absolute;
background: antiquewhite;
width: 300px;
}

.child {
position: absolute;
background: yellow;
width: calc(100% - 20px);
height: 50px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="add">add</button>
<button id="remove">remove</button>

<div class="parent">
<div class="child" style="position: absolute;">
Div one
</div>

<div class="child" style="position: absolute; top: 50px;">
div two
</div>
<div class="child" style="position: absolute; top: 100px;">
div three
</div>
</div>

关于jquery - 根据子元素的变化增加或减少父 div 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com