<!DOCTYPE html>
<html lang="en">
<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>js01/ex03</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
<!-- Popper JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<style>
div.box{
border: 1px solid red;
background-color: skyblue;
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<h2>자바스크립트 function 예제3</h2>
<div class="box">Box01</div>
<script>
var box = document.querySelector('div.box');
// 화살표 함수에서 this는 window
// function에서 this는 이벤트가 발생한 객체
// on으로 시작하는 속성에 이벤트 핸들러 사용 가능
box.addEventListener('mousedown', function(e){
var gapX = e.clientX - box.offsetLeft;
var gapY = e.clientY - box.offsetTop;
//console.log(e.currentTarget);
//console.log(e.clientX, e.clientY);
function moveHandler(e2){
box.style.left = e2.clientX - gapX + 'px';
box.style.top = e2.clientY - gapY + 'px';
}
window.addEventListener('mousemove', moveHandler)
box.addEventListener('mouseup', function(){
window.removeEventListener('mousemove', moveHandler)
});
});
</script>
</body>
</html>
'2022 SW전문인재양성사업 > 웹 프로그래밍 기본' 카테고리의 다른 글
Javascript (6) - 드래그 앤 드롭 실습2 (0) | 2022.07.27 |
---|---|
Javascript (5) - 드래그 앤 드롭 실습1 (0) | 2022.07.27 |
Javascript (4) - 박스 이동 함수 (0) | 2022.07.27 |
Javascript (2) - 함수 호출 관련 (0) | 2022.07.27 |
Javascript (1) - 기초 (0) | 2022.07.27 |