我遇到了一个我想避免的奇怪(可能不是)行为,因为最终结果是一种可怕的用户体验。为了帮助您了解问题,我将下面的代码段放在一起。
var counter;
var counterDisplay;
var intervalRef;
window.onload = function(){
console.log("loading");
counter = 11;
counterDisplay = document.getElementById("spCounter");
intervalRef = setInterval(tickHandler, 1000);
};
function tickHandler(){
counter--;
counterDisplay.innerHTML = counter.toString();
if(counter == 0){
stop();
return;
}
}
function stop(){
clearInterval(intervalRef);
document.getElementById("daddyLongLegs").style.display = "block";
}
html,body{
width:100%;
height:100%;
font-family:Arial;
font-size:16px;
}
.page-wrapper{
height:100%;
background-color:#eee;
}
.growing-element{
height:800px;
display:none;
margin: 100px 100px 0 100px;
background-color:#ddd;
}
<div class="page-wrapper">
<div class="container-element">
<!--This element's height never changes once the page has been rendered-->
<div>
The hidden child element below will magically appear in: <span id="spCounter">10</span> seconds
</div>
<!--This element's height changes anytime after the page has been loaded-->
<div id="daddyLongLegs" class="growing-element">
Now you see me...
</div>
</div>
</div>
代码片段非常简单,所有javascript都是在十秒钟后显示子元素(#daddyLongLegs
)。使“问题”更加直观地呈现与子元素不同的父元素(div.container-element
)。
现在,当10秒后显示子元素(#daddyLongLegs
)时,它似乎不会“拉伸”父元素(div.container-element
)。这不是我想要实现的行为。我希望父元素在其内容发生变化时重新调整其高度。但是,重要的是父元素的高度始终覆盖整个文档
如果内容发生变化,如何让父母重新调整其高度?是否有纯css解决方案?
答案 0 :(得分:3)
.container-element
的定义高度为100%
如果删除它,或将其设置为auto
,则应根据其内容计算高度。
或者您可以从height
更改为min-height
,这会根据其内容计算高度,但不得低于其父级高度的100%。
答案 1 :(得分:1)
正如MDN所述,您可以使用min-height
属性代替height
,因此,只要您的<div>
孩子上升,它就会延长父母
所以我的评论:
使用
min-height: 100%
代替height: 100%
.page-wrapper
答案 2 :(得分:-1)
将高度更改为100%,将边距更改为0;
var counter;
var counterDisplay;
var intervalRef;
window.onload = function(){
console.log("loading");
counter = 5;
counterDisplay = document.getElementById("spCounter");
intervalRef = setInterval(tickHandler, 1000);
};
function tickHandler(){
counter--;
counterDisplay.innerHTML = counter.toString();
if(counter == 0){
stop();
return;
}
}
function stop(){
clearInterval(intervalRef);
document.getElementById("daddyLongLegs").style.display = "block";
}
&#13;
html,body{
width:100%;
height:100%;
font-family:Arial;
font-size:16px;
}
.page-wrapper{
height:100%;
background-color:#eee;
}
.growing-element{
height:100%;
display:none;
background-color:#ddd;
}
&#13;
<div class="page-wrapper">
<div class="container-element">
<!--This element's height never changes once the page has been rendered-->
<div>
The hidden child element below will magically appear in: <span id="spCounter">10</span> seconds
</div>
<!--This element's height changes anytime after the page has been loaded-->
<div id="daddyLongLegs" class="growing-element">
Now you see me...
</div>
</div>
</div>
&#13;