【发布时间】:2019-07-04 17:40:16
【问题描述】:
我有一个类似终端的 contentEditable div。我想要新的输出使其滚动窗口以便它在视图中,除非用户手动移动滚动条以查看另一个位置。在这种情况下,我希望让它查看他们所在的位置。
如果可能的话,我宁愿避免使用 JavaScript 钩子或计时器回调来执行此操作。所以我对使用display: flex 和flex-direction: column-reverse; 的a promising CSS-only solution 很感兴趣。 (对该解决方案的评论解释说,您可以通过使用带有属性的外部容器来避免元素反转的麻烦。)
从另一个答案中借用一个 sn-p,这里演示了这种技术在我的浏览器中有效——但仅适用于固定大小的 div。
const inner = document.getElementById("inner")
let c = 0
setInterval(function() {
const newElement = document.createElement("div")
newElement.textContent = "Line #" + (++c)
inner.appendChild(newElement)
}, 500)
#outer { /* contents of this div are reversed */
height: 100px;
display: flex;
flex-direction: column-reverse;
overflow: auto;
}
#inner { /* this div has content in normal order */
}
<div id="outer"><div id="inner"></div></div>
<p>To be clear: We want the scrollbar to stick to the bottom if we have scrolled all the way down. If we scroll up, then we don't want the content to move.</p>
但将其更改为 100% 反而会破坏它。height: auto 也是如此。我可以应用什么魔法来保持行为并使用 100% 的高度?
const inner = document.getElementById("inner")
let c = 0
setInterval(function() {
const newElement = document.createElement("div")
newElement.textContent = "Line #" + (++c)
inner.appendChild(newElement)
}, 500)
#outer { /* contents of this div are reversed */
height: auto;
display: flex;
flex-direction: column-reverse;
overflow: auto;
}
#inner { /* this div has content in normal order */
}
<div id="outer"><div id="inner"></div></div>
<p>Having changed it to 100%, new content never gets scrolled into view, even if the scroll bar was "stuck" to the bottom</p>
【问题讨论】:
标签: javascript css flexbox scrollbar