1. 설명
마우스로 드래그가 가능한 모달창을 만든다.
모달창의 타이틀부분( h1Tag ) 드래그시에만 모달창이 이동 가능하고,
드래그시 모달창( this.modal )이 움직인다.
모달창의 사용자 속성 x, y 값을 저장해주고,
마우스가 움직이면 마우스 이벤트의 이동값 만큼 움직일 좌표를 변수 x ,y에 저장.
그 후에 사용자 속성 x, y의 값을 다시 현재 위치로 수정해주고, 모달창을 변수 x, y로 이동
2. 코드
드래그 관련 코드는 drag() 메소드쪽에 있다.
import View from "./view";
type ModalModel = {
title : string
}
export class Modal extends View{
modal : View;
is_drag : boolean = false;
constructor(model : ModalModel) {
super("simms-modal-container", document.body);
this.modal = new View("simms-modal", this);
let h1Tag = new View("h1", this.modal).html(model.title);
this.drag(h1Tag);
new View("main", this.modal);
}
add(view : View){
this.modal.el.querySelector("main")?.append(view.el);
}
drag(h1Tag: View){
h1Tag.el.addEventListener("mousedown", e => {
this.is_drag = true;
this.modal.el.dataset.x = String(e.clientX);
this.modal.el.dataset.y = String(e.clientY);
});
this.el.addEventListener("mousemove", e => {
if(!this.is_drag) return;
else if(this.modal.el.dataset.x && this.modal.el.dataset.y){
const x = parseInt(this.modal.el.dataset.x) - e.clientX;
const y = parseInt(this.modal.el.dataset.y) - e.clientY;
this.modal.el.dataset.x = String(e.clientX)
this.modal.el.dataset.y = String(e.clientY)
this.modal.el.style.top = `${this.modal.el.offsetTop - y}px`;
this.modal.el.style.left = `${this.modal.el.offsetLeft - x}px`;
}
});
this.el.addEventListener("mouseup", e => {
this.is_drag = false;
});
this.el.addEventListener("mouseleave", e => {
this.is_drag = false;
});
}
}
반응형
'Client Side' 카테고리의 다른 글
Array.reduce() (0) | 2023.04.05 |
---|---|
Drag And Drop (0) | 2023.04.05 |
Datepicker MinDate (0) | 2023.01.30 |
필수사항 체크 (0) | 2023.01.27 |
async & await (0) | 2023.01.27 |