<div id="layer">
Drag
<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;}
.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);}
const flexContainer = document.getElementById('layer');
let dragging = false,
xPos, // X축 좌표 변수 선언
yPos; // Y축 좌표 변수 선언
// 마우스 클릭
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);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.