728x90
웹 페이지에 기둥을 하나 만들어서 좌우로 리사이징을 하는 JS
// Query the element
const resizer = document.getElementById("resizer");
const leftSide = resizer.previousElementSibling;
const rightSide = resizer.nextElementSibling;
// The Current Position of mouse
let x = 0;
let y = 0;
// Width of left side
let leftWidth = 0;
// Handle the mousedown event
// that's triggered when user drags the resizer
const mouseDownHandler = function (e) {
// Get the current mouse position
x = e.clientX;
y = e.clientY;
leftWidth = leftSide.getBoundingClientRect().width;
// Attach the listeners to `document`
document.addEventListener("mousemove", mouseMoveHandler);
document.addEventListener("mouseup", mouseUpHandler);
};
const mouseMoveHandler = function (e) {
// How far the mouse has been moved
const dx = e.clientX - x;
const dy = e.clientY - y;
const newLeftWidth =
((leftWidth + dx) * 100) / resizer.parentNode.getBoundingClientRect().width;
leftSide.style.width = `${newLeftWidth}%`;
document.body.style.cursor = "col-resize";
leftSide.style.userSelect = "none";
leftSide.style.pointerEvents = "none";
rightSide.style.userSelect = "none";
rightSide.style.pointerEvents = "none";
};
const mouseUpHandler = function () {
resizer.style.removeProperty("cursor");
document.body.style.removeProperty("cursor");
leftSide.style.removeProperty("user-select");
leftSide.style.removeProperty("pointer-events");
rightSide.style.removeProperty("user-select");
rightSide.style.removeProperty("pointer-events");
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener("mousemove", mouseMoveHandler);
document.removeEventListener("mouseup", mouseUpHandler);
};
const mouseOverHandler = function () {
document.body.style.cursor = "col-resize";
};
const mouseLeaveHandler = function () {
resizer.style.removeProperty("cursor");
document.body.style.removeProperty("cursor");
};
// Attach the handler
resizer.addEventListener("mousedown", mouseDownHandler);
resizer.addEventListener("mouseover", mouseOverHandler);
resizer.addEventListener("mouseleave", mouseLeaveHandler);
'JavaScript' 카테고리의 다른 글
Uncaught SyntaxError: Invalid shorthand property initializer 해결 (0) | 2023.02.27 |
---|---|
Javascript 날짜 계산기 (0) | 2023.01.31 |
Swiper <DevTools failed to load source map> (0) | 2022.12.08 |
TypeError: ws.Server is not a constructor (0) | 2022.11.01 |
Element Resize 시 window resize 이벤트 발생 속도 (0) | 2022.10.31 |