0
点赞
收藏
分享

微信扫一扫

可拖动的分隔条来调整两个 div 的宽度,js实现

<template>
  <div id="container" ref="container">
    <div id="left-panel" :style="{ width: leftWidth + 'px' }">
      左侧面板
    </div>
    <div id="splitter" @mousedown="startDrag">
      ||
    </div>
    <div id="right-panel">
      右侧面板
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const container = ref(null);
const leftWidth = ref(200); // 设置左侧面板的初始宽度

function startDrag(event) {
  const startX = event.clientX;
  const startWidth = leftWidth.value;

  function onMouseMove(e) {
    const currentX = e.clientX;
    leftWidth.value = startWidth + (currentX - startX);

    // Optional: Limit the width so it doesn't go too small or too large
    if (leftWidth.value < 100) leftWidth.value = 100;
    if (leftWidth.value > container.value.offsetWidth - 100) {
      leftWidth.value = container.value.offsetWidth - 100;
    }
  }

  function onMouseUp() {
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
  }

  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
}
</script>

<style>
#container {
  display: flex;
  height: 100%;
}

#left-panel {
  background-color: #ddd;
  height: 100%;
  overflow: auto;
}

#splitter {
  background-color: #888;
  width: 5px;
  cursor: col-resize;
  user-select: none; /* Prevent text selection while dragging */
}

#right-panel {
  background-color: #bbb;
  flex-grow: 1;
  height: 100%;
  overflow: auto;
}
</style>

举报

相关推荐

0 条评论