<div id="layer">
Draggable & Resizable Layer
<span class="resize"></span>
</div>
* {margin: 0; padding: 0; width: 100%; height: 100%; box-sizing: border-box;}
body {position: relative;}
#layer {width: 200px; height: 200px;position: absolute; display: block; top: 50px; left: 40px; background-color: #ccc; border-radius: 15px; padding: 30px; min-width: 200px; min-height: 100px;}
.resize {display: block; position:absolute; right: -10px; bottom: -10px; width: 20px; height: 20px; border: 10px solid #000; border-top: none; border-left: 10px solid transparent; border-right: 10px solid transparent; cursor: resize; transform: rotate(135deg); z-index:10;}
const flexContainer = document.getElementById('layer');
const resizePointer = document.querySelector('.resize'); // 리사이즈 이벤트 실행 포인트 변수 선언
let dragging = false,
xPos, // X축 좌표 변수 선언
yPos, // Y축 좌표 변수 선언
initWidth, // 레이어 최초 넓이 변수 선언
initHeight; // 레이어 최초 높이 변수 선언
// 마우스 클릭
function dragStart(e) {
e.preventDefault(); // 브라우저 기본 이벤트를 방지
xPos = e.clientX; // 현재 마우스 X축 위치값을 변수에 대입
yPos = e.clientY; // 현재 마우스 Y축 위치값을 변수에 대입
dragging = true; // dragging 설정을 활성화
};
function dragMove(e) {
if(dragging) {
const currentPosx = xPos - e.clientX, // 현재 X축값 변수 선언
currentPosY = yPos - e.clientY; // 현재 Y축값 변수 선언
xPos = e.clientX; // 움직이는 마우스 X축 값을 변수에 대입
yPos = e.clientY; // 움직이는 마우스 Y축 값을 변수에 대입
flexContainer.style.left = `${flexContainer.offsetLeft - currentPosx}px`; // drag layer에 마우스가 위치한 x축 값을 선언
flexContainer.style.top = `${flexContainer.offsetTop - currentPosY}px`; // drag layer에 마우스가 위치한 y축 값을 선언
}
};
function dragEnd(e) {
dragging = false; // 마우스 클릭이 해제 되었을 경우 선언
};
flexContainer.addEventListener("mousedown", dragStart);
document.addEventListener("mousemove", dragMove);
document.addEventListener("mouseup", dragEnd);
// 마우스 클릭
function initDrag(e) {
xPos = e.clientX; // 현재 마우스 X축 위치값을 변수에 대입
yPos = e.clientY; // 현재 마우스 Y축 위치값을 변수에 대입
initWidth = parseInt(window.getComputedStyle(flexContainer).width, 10);
initHeight = parseInt(window.getComputedStyle(flexContainer).height, 10);
document.addEventListener("mousemove", resizing);
document.addEventListener("mouseup", stopResize);
};
function resizing(e) {
e.preventDefault();
flexContainer.style.width = `${(initWidth + e.clientX - xPos)}px`;
flexContainer.style.height = `${(initHeight + e.clientY - yPos)}px`;
};
function stopResize(e) {
document.removeEventListener("mousemove", resizing);
document.removeEventListener("mouseup", stopResize);
};
resizePointer.addEventListener("mousedown", initDrag);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.