如何使滚动条只在一个div中



我想在页面中添加两个div,一个div用于顶部,仅可编辑,另一个div用于下部,可编辑。我想要实现的是:

  1. 如果内容太长,请使下部Div可编辑和滚动
  2. 滚动下方Div时,上方Div应保持在相同位置

这是我的代码:

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

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

那么,如何使滚动条仅应用于较低的Div?

滚动条当前应用于整个窗口,因此页面上的所有元素都会一起上下滚动。一种选择是使可编辑区域可滚动。限制该区域的高度并将其溢出设置为"0";自动;或";滚动";。

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


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

在下面的演示中,<body>被划分为两个区域:顶部区域和底部";可滚动容器";填充剩余窗口高度的区域。底部区域限制可编辑/可滚动区域的最大高度。

我还加了一个";占位符";这里讨论的技术:内容可编辑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>

最新更新