728x90
반응형
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="inputEvent.js" defer></script>
    
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: #FFF700;
            border: 5px solid red;
            cursor : pointer;
        }
    </style>

</head>
<body>
    <div class="box"></div>
</body>
</html>
300x250
반응형
const box = document.querySelector('.box');
const initMousPos = {x:0, y:0};//리터럴 객체생성방법 // 마우스 드래그 시작 지점의 위치
// functioninitMouserPos(){
//     this.x = 0;
//     this.y = 0;
// }
const offset = {x : 0, y : 0}; //이동할 거리
// mousemove시 실행할 move함수
const move = function(event){
    // 이동할 거리 = 현재 (드래그 진행 시점)의 마우스 위치 - (드래그 시작 지점의 마우스 위치)
    offset.x = event.clientX - initMousPos.x;
    offset.y = event.clientY - initMousPos.y;
    // translate3d는 GPU를 사용하기 떄문에 top, left 속성을 변경하는 것보다 처리 속도가 빠름
    // top, left는 레이아웃에 영햘을 줌
    box.style.transform = `translate3d(${offset.x}px, ${offset.y}px,0)`;
};
// mousedown : 마우스가 눌렸다(클릭아님)
// mousedown 이벤트 발생 시, 드래그 시작 시점의 마우스 포인터 좌표(event.clientX 와 clientY)를 저장해 둡니다.
// 
box.addEventListener('mousedown', event =>{
    initMousPos.x = event.clientX - offset.x;
    initMousPos.y = event.clientY - offset.y;
    // mousedown 이벤트가 발생한 상태에서 mousemove 이벤트가 발생하면 box를 이동시키는 move를 실행
    document.addEventListener('mousemove', move);
});
// mouseup : 마우스를 떄는 이벤트(클릭 아님)가 발생하면 move 이벤트를 하면 안되므로 제거해준다
document.addEventListener('mouseup', () =>{
    document.removeEventListener('mousemove', move);
});


 

 

마우스로 클릭 후 이동 가능한 네모난 상자만들기

728x90
반응형

'코딩일지 > WEB' 카테고리의 다른 글

setTimeout / setInterval 사용 요약  (0) 2023.01.03
addEventListener 활용2  (0) 2023.01.03
js 기초6  (0) 2023.01.03
js 기초5  (0) 2023.01.01
js 정규식 연습1  (0) 2023.01.01

+ Recent posts

">