Skip to main content
席宇博客

欢迎访问席宇博客

移动端上拉抽屉效果

移动端抽屉 #

移动端上拉抽屉是一种常见的交互效果,可以在屏幕底部显示一个可拖动的视图,用于展示更多的内容或功能。实现这种效果的代码有多种方式,这里介绍一种基于CSS和JavaScript的demo,代码和演示效果如下。

demo仅在移动端有效,pc端无效

<!DOCTYPE html>
<html>
<head>
  <title>移动端拖住增加元素高度</title>
  <style>
    #drag-element {
      width: 100%;
      height: 200px;
      background-color: rgb(46, 228, 197);
      margin: 50px auto;
      position: absolute;
      bottom: 0;
      max-height: 90%;
    }
  </style>
</head>
<body>
  <div id="drag-element"></div>
  <script>
    const element = document.getElementById('drag-element');
    let initialTouchPosition;
    let initialElementHeight;
    element.addEventListener('touchstart', (event) => {
      initialTouchPosition = event.touches[0].clientY;
      initialElementHeight = element.offsetHeight;
    });
    element.addEventListener('touchmove', (event) => {
      const currentTouchPosition = event.touches[0].clientY;
      const touchDistance = initialTouchPosition - currentTouchPosition;
      const newElementHeight = initialElementHeight + touchDistance;
      element.style.height = `${newElementHeight}px`;
    });
    element.addEventListener('touchend', () => {
      initialTouchPosition = null;
      initialElementHeight = null;
    });
  </script>
</body>
</html>

DEMO #

示例如下,打开移动端抽屉DEMO查看