我试图将一段文本设置为显示为修剪/短版,然后使用动画显示完整的文本 block ,因此我将它们放入两个不同的元素中,并基于隐藏/显示您可以在哪一个上看到。
这是我的示例代码,文本有所不同,但这只是我正在做的一个例子。我的问题是我需要始终确保 #next 中的绿色文本 block 始终显示在 red 或 blue 文本 block 之后。
HTML:
<div class="wrapper">
<div id="parent">
<div id="short">
Only a small amount of text
</div>
<div id="long" style="display: none">
A much longer text with <br>
some lines<br>
...<br>
...<br>
...<br>
...<br>
Surprise!
</div>
</div>
</div>
<div id="next">
Other content<br>
to show up<br>
here<br>
<button onclick="toggle()">TOGGLE TEXT</button>
</div>
JS:
toggle = function() {
var lElem = $('#long');
var sElem = $('#short');
if (lElem.css('display') == 'none') {
sElem.hide('fast');
lElem.show('fast');
} else {
lElem.hide('fast');
sElem.show('fast');
}
}
CSS:
.wrapper {
height: auto;
}
#parent {
position: absolute;
}
#short, #long {
position: relative;
}
#short {
background-color: red;
}
#long {
background-color: blue;
}
#next {
background-color: green;
font-size: 3em;
}
JsFiddle : http://jsfiddle.net/6v9fyg2g/
我试过 position: absolute 和 relative 以及添加 height: 100% 但这似乎没有解决问题。
最佳答案
只要next
不是parent
的子节点并且parent
是absolute,您就无法实现您想要的。 .
来自 MDN:
absolute
: Do not leave space for the element. Instead, position it at a specified position relative to its closest positioned ancestor or to the containing block. Absolutely positioned boxes can have margins, they do not collapse with any other margins.
(强调我的)。
在这种情况下发生的事情是 parent
被放置在 (0,0)
和布局的其余部分,包括 next
, 的流动不考虑 parent
,因此 next
在所有意图和目的中都被视为第一个元素,并在开头结束。
一种可能的解决方案是从 parent
中删除 position: absolute
。
然后,根据您的要求,“#next
中的绿色文本 block 始终显示在红色或蓝色文本 block 之后”,如下所示:
http://jsfiddle.net/6v9fyg2g/4/
然后您可以根据需要调整 divs
的其他属性(例如宽度)。
您可能想要 display: inline
或 inline-block
它们对于初学者来说(第二个选项看起来更接近 divs
在您的原始版本中的显示方式):
关于html - 包装器 div 的正确高度的绝对/相对位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32712105/