【问题标题】:Allow overflow of child element while maintaining scrollability of parent允许子元素溢出,同时保持父元素的可滚动性
【发布时间】:2021-08-26 14:15:49
【问题描述】:

我有一个可滚动容器内的弹出窗口。我希望弹出窗口在打开时溢出容器外,但希望容器上的其余子元素保持可滚动状态。将position: absolute 添加到弹出窗口将解决问题,但如果用户滚动它会使弹出窗口保持在同一位置,所以我不能这样做。

在附加的代码 sn-p 中,当您单击“打开”按钮时,红色的弹出窗口应该从父容器流出(因为它的宽度大于父容器的宽度)。但是你可以看到它只被限制在它的父宽度上。您还可以在容器中滚动以验证滚动行为。

如果可能,我更喜欢仅使用 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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    包装div 和“其他内容”divs 的内容,以便它们与显示弹出窗口的位置分开。然后使用 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>

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多