我在可滚动容器内有一个弹出窗口。我希望弹出窗口在打开时溢出到容器外,但希望容器上的其余子元素保持可滚动。将 position: absolute
添加到 popup 将解决问题,但如果用户滚动,它会使弹出窗口保持在同一位置,所以我不能那样做。
在附加的代码片段中,当您单击“打开”按钮时,红色弹出窗口应流出父容器(因为其宽度大于父容器的宽度)。但是您可以看到它仅受其父宽度的限制。您还可以在容器中滚动以验证滚动行为。
如果可能,我更喜欢仅使用 css 的解决方案。
const button = document.getElementById('open');
button.addEventListener('click', () => {
const child = document.querySelector('.child');
child.insertAdjacentHTML('afterbegin', '<div class="popup"></div>');
});
.container {
width: 100px;
height: 100px;
border: 1px solid black;
overflow-y: scroll;
}
.child {
height: 300px;
}
.popup {
width: 150px;
height: 50px;
background: red;
}
<div class="container">
<div class="child">
<button id="open">Open</button>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
</div>
</div>
答案 0 :(得分:0)
将 div
的内容和“其他内容”div
包裹起来,以便它们与弹出窗口的显示位置分开。然后使用 JavaScript 计算高度。
const other = document.querySelector('.other');
var start = 100;
const button = document.getElementById('open');
button.addEventListener('click', () => {
const child = document.querySelector('.child');
child.insertAdjacentHTML('afterbegin', '<div class="popup"></div>');
start -= 50;
other.style.height = start + "px";
});
.container {
width: 100px;
height: 100px;
border: 1px solid black;
}
.popup {
width: 150px;
height: 50px;
background: red;
}
.other {
height: 100px;
overflow: hidden;
}
<div class="container">
<div class="child">
<div class="other">
<button id="open">Open</button>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
<div>other content</div>
</div>
</div>
</div>