如果div的内容导致div的垂直滚动,那么实现想要div-container的设计的最佳方法是提供边框?
CSS
div {
max-height: 100px;
overflow-y: auto;
// if content exceeds 100 px show border
border: solid 1px;
}
HTML
<div>
// Text ..
</div>
答案 0 :(得分:2)
如果溢出则设置边框。
var div = document.querySelector('div');
if (div.scrollHeight > div.clientHeight) {
div.style.border = '1px solid';
}
&#13;
div {
max-height: 100px;
overflow-y: auto;
}
&#13;
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
&#13;
答案 1 :(得分:0)
我假设某种事件会改变或决定该div的内容。 以我的拙见,你无法单独使用html / css。你必须使用JavaScript。 https://jsfiddle.net/4u2Lurt3/
这是一个如何做到这一点的简单示例。您可能需要以不同方式“重新连线”以获得您想要的确切行为
<div id="myDiv">
Hello
</div>
<button onclick="addText()">
Click to change div
</button>
和
function checkWidth() {
var div = document.getElementById('myDiv');
if(div.offsetWidth > 100) {
div.style.border = "1px solid black"
}
}
function addText() {
var div = document.getElementById('myDiv');
div.style.width="250px";
div.innerText = "AAAAAAAAAAAAA VVVVVVEERRRRY LOOOONNNNGGG TEEEEEXXXXXTT";
checkWidth();
}