繁体   English   中英

如何只在一个div中制作滚动条

[英]How to make scrollbar in one div only

我想在页面中添加两个Div,一个Div用于顶部,它是只读的,另一个Div用于底部,它是可编辑的。 我想要实现的是:

  1. 如果内容太长,请将下方的 Div 设置为可编辑和可滚动。
  2. 滚动较低的 Div 时,顶部的 Div 应保持不变 position

这是我的代码:

 <html> <body> <div> <div>Top Part</div> <div contenteditable="true">Click here to type</div> </div> </body> </html>

在上面的代码中,如果我点击下面的Div,我们就可以输入,然后如果我们一直按回车,它会显示垂直滚动条,但是如果我滚动,顶部的Div也会向上滚动,这是我想要的避免。

那么,怎样才能让滚动条只作用于下层的Div呢?

滚动条当前应用于整个 window,因此页面上的所有元素一起上下滚动。 一种替代方法是使可编辑区域可滚动。 限制该区域的高度并将其溢出设置为“自动”或“滚动”。

 .edit { max-height: 5em; overflow-y: auto; }
 <div> <div>Top Part</div> <div contenteditable="true" class="edit">Click here to type</div> </div>


您可以通过使用 window 高度作为限制器来避免为可滚动区域设置特定高度。 一种方法是使用 flexbox 使可滚动区域填充剩余的 window 高度。 这是一个例子 在您的情况下, <body>可以是“外部” flexbox 容器。

在下面的演示中, <body>被分成两个区域:顶部区域和填充剩余 window 高度的底部“可滚动容器”区域。 底部区域限制了可编辑/可滚动区域的最大高度。

我还添加了此处讨论的“占位符”技术: Placeholder for contenteditable div

 html, body { margin: 0; } body { height: 100vh; display: flex; flex-direction: column; }.header { background-color: #EEF; }.scroll-container { flex: 1; min-height: 1em; }.scrollable { max-height: 100%; overflow-y: auto; }.header, .scrollable { padding: 0.5em; box-sizing: border-box; } [contenteditable=true]:empty:before { content: attr(data-placeholder); color: grey; font-style: italic; cursor: text; }
 <div class="header">Top Part</div> <div class="scroll-container"> <div contenteditable="true" class="scrollable" data-placeholder="Click here to type"></div> </div>

如果您的意思是希望顶部始终在顶部可见,则可以使用position: sticky

 .sticky { font-size: 2em; position: sticky; top: 0; } [contenteditable=true] { border: 0.1em solid black; }
 <html> <body> <div> <div class="sticky">Top Part</div> <div contenteditable="true">Click here to type</div> </div> </body> </html>

你可以这样做:

 .scrollable{ overflow-y: scroll; max-height: 150px; }
 <html> <body> <div> <div>Top Part</div> <div class="scrollable" contenteditable="true">Click here to type</div> </div> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM