0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

なにもわからないAdvent Calendar 2024

Day 4

カーテンみたいに横から引き出すdiv

Posted at

はじめに

右側にユーザーが幅変更可能な設定メニュー欄を置くために、見つけたコードを見つけたので、少し改良しました。

moving_div.gif

参考資料

stack overflow: Resize a div on border drag and drop without adding extra markup

コード

index.html
<div id="right_panel"></div>
style.css
#right_panel {
  position: absolute;
  width: 96px;
  min-width: 50px;
  max-width: 500px;
  height: 100%;
  right: 0;
  background-color: #d4ddff;
  cursor: ew-resize;
}

/* 境界線用 */
#right_panel::after {
  content: '';
  background-color: #ccc;
  position: absolute;
  left: 0;
  width: 4px;
  height: 100%;
  cursor: ew-resize;
}
panel.js
const panel = document.getElementById("right_panel");
const BORDER_SIZE = 4; // リサイズ可能な領域の幅
const MIN_WIDTH = 50; // 最小幅
const MAX_WIDTH = 500; // 最大幅

let isResizing = false;
let startX = 0;

panel.addEventListener("mousedown", (e) => {
  if (e.offsetX < BORDER_SIZE) {
    isResizing = true;
    startX = e.clientX;
    document.addEventListener("mousemove", resize);
    document.addEventListener("mouseup", stopResize);
  }
});

function resize(e) {
  if (!isResizing) return;
  const dx = e.clientX - startX;
  startX = e.clientX;
  const newWidth = Math.min(
    Math.max(panel.offsetWidth - dx, MIN_WIDTH),
    MAX_WIDTH
  );
  panel.style.width = `${newWidth}px`;
}

function stopResize() {
  isResizing = false;
  document.removeEventListener("mousemove", resize);
  document.removeEventListener("mouseup", stopResize);
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?