transform & fixed

transform元素影响fixed元素

by junhui

HTML

<div class="button">
  按我弹出或隐藏底部面板
</div>
<div class="select-pop">
  <div class="panel">
    <div id="container-transform">
      <div class="fixed-to-container"></div>
      <p class="text">
        这是测试文字,你会发现此时fixed元素已经不是我们认识的fixed元素了,这些文字不再穿过fix元素,fixed元素会随着滚动条滚动而滚动。那如果我们既需要fixed元素不相对于viewport定位,又能有fixed元素原本的作用呢?该怎么办?这是测试文字,你会发现此时fixed元素已经不是我们认识的fixed元素了,这些文字不再穿过fix元素,fixed元素会随着滚动条滚动而滚动。那如果我们既需要fixed元素不相对于viewport定位,又能有fixed元素原本的作用呢?该怎么办?这是测试文字,你会发现此时fixed元素已经不是我们认识的fixed元素了,这些文字不再穿过fix元素,fixed元素会随着滚动条滚动而滚动。那如果我们既需要fixed元素不相对于viewport定位,又能有fixed元素原本的作用呢?该怎么办?
      </p>
    </div>
  </div>
</div>

CSS

.button {
  width: 250px;
  height: 50px;
  border: 1px solid #e5e5e5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.select-pop {
  position: fixed;
  left: 0;
  top: 100%;
  width: 100%;
  height: 100vh;
  color: #666;
  transform: translate3d(0, 0, 0);
}

.panel {
  position: absolute;
  left: 0;
  top: 0px;
  width: 100%;
  background: #f0f1f2;
  z-index: 95;
  transition: all 0.5s;
  transform: translate(0, 0%);
}

.panel-show {
  transform: translate(0, -100%);
}

#container-transform {
  max-height: 200px;
  overflow-y: scroll;
  background: #fff;
}

.fixed-to-container {
  width: 100%;
  height: 50px;
  border: 1px solid #999;
  position: fixed;
  top: 0px;
  left: 0px;
  background-color: rgba(0, 0, 0, .4);
}

.text {
  padding-top: 50px;
}

JavaScript

const btn = document.querySelector('.button')
btn.addEventListener('click', () => {
  const panel = document.querySelector('.panel')
  if (panel.className.match('panel-show')) {
    panel.className = panel.className.replace('panel-show', '')
  } else {
    panel.className += ' panel-show'
  }
})