split window-純js+css範例

by cactus77kiki

HTML

<link rel="stylesheet" href="T10-Splitter.css">
<script src="T10-Splitter.js"></script>

<body onload="onload()">
<div class="splitter">
	<div id="first"></div>
	<div id="seperator"></div>
	<div id="second"></div>
</div>
</body>

<script>
function onload()
{
	dragElement( document.getElementById("seperator"), "H" );
}

// function is used for dragging and moving
function dragElement( element, direction, handler )
{
  // Two variables for tracking positions of the cursor
  const drag = { x : 0, y : 0 };
  const delta = { x : 0, y : 0 };
  /* if present, the handler is where you move the DIV from
     otherwise, move the DIV from anywhere inside the DIV */
  handler ? ( handler.onmousedown = dragMouseDown ): ( element.onmousedown = dragMouseDown );

  // function that will be called whenever the down event of the mouse is raised
  function dragMouseDown( e )
  {
    drag.x = e.clientX;
    drag.y = e.clientY;
    document.onmousemove = onMouseMove;
    document.onmouseup = () => { document.onmousemove = document.onmouseup = null; }
  }

  // function that will be called whenever the up event of the mouse is raised
  function onMouseMove( e )
  {
    const currentX = e.clientX;
    const currentY = e.clientY;

    delta.x = currentX - drag.x;
    delta.y = currentY - drag.y;

    const offsetLeft = element.offsetLeft;
    const offsetTop = element.offsetTop;

	
	const first = document.getElementById("first");
	const second = document.getElementById("second");
	let firstWidth = first.offsetWidth;
	let secondWidth = second.offsetWidth;
  if (direction === "H" ) // Horizontal
	{
		element.style.left = offsetLeft + delta.x + "px";
		firstWidth += delta.x;
		secondWidth -= delta.x;
	}
    drag.x = currentX;
    drag.y = currentY;
	first.style.width = firstWidth + "px";
	second.style.width = secondWidth + "px";
  }
}
</script>

CSS

.splitter {
	width: 500px;
	height: 100px;
	display: flex;
}

#seperator {
	cursor: col-resize;
	background: url(https://raw.githubusercontent.com/RickStrahl/jquery-resizable/master/assets/vsizegrip.png) center center no-repeat #535353;	
	width: 10px;
	height: 100px;
	min-width: 10px;
}

#first {
	background-color: green;
	width: 100px;
	height: 100px;
	min-width: 10px;
}

#second {
	background-color: red;
	width: 390px;
	height: 100px;
	min-width: 10px;
}

JavaScript

/*
ref:https://stackoverflow.com/questions/12194469/best-way-to-do-a-split-pane-in-html
Best way to do a split pane in html(answered Sep 27 '18 at 12:10 Reza)
*/