【发布时间】:2021-01-25 21:38:46
【问题描述】:
我正在尝试将 <div> 幻灯片打开到包含其内容而不会溢出的最小尺寸。
这是我目前所得到的:
window.onload = function() {
setTimeout(() => {
var thing = document.getElementById('thing');
thing.style.maxWidth = thing.scrollWidth + "px";
thing.style.maxHeight = thing.scrollHeight + "px";
}, 1000);
}
body {
background-color: black;
}
p {
margin: 40px;
padding: 0;
color: yellow;
background-color: green;
font-family: monospace;
}
div.expander {
margin: 0;
padding: 0;
max-width: 0;
max-height: 0;
overflow: hidden;
transition:
max-width 1s,
max-height 1s;
border: 1px solid red;
}
hr {
margin: 0;
padding: 0;
border-top: 1px solid blue;
border-right: none;
border-bottom: none;
border-left: none;
}
<div id="thing" class="expander">
<p>Hello, world!</p>
<hr>
<p>Goodbye, world!</p>
</div>
看看<p> 的宽度如何不足以容纳其文本而不会溢出?这就是我试图阻止的。显然,scrollHeight 正在做我期望的事情。为什么不是scrollWidth?
【问题讨论】:
-
制作
p {display:inline-block;}。我不确定为什么会这样。 -
您希望将文本换行(2 行)吗?如果没有,请将
white-space: nowrap;添加到您的 p 样式中。
标签: javascript css