HTD
[Vanilla JS] Drag&Drop 드래그앤드롭 본문
좀 무섭네요
그냥 원을 움직이는 건 너무 심심해서 이미지 하나 넣어본 것 뿐이에요 별 다른 기능은 없습니다.
HTML/CSS
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js-dragdrop.js"></script>
</head>
<body>
<style>
.target{
display: flex;
position: absolute;
left: 50px;
top: 50px;
border-radius: 20px;
width: 40px;
height: 40px;
background-color: #4c3832;
cursor: pointer;
}
</style>
<img class="background" src="쿠마.png" width=500px></img>
<a class="target"> </a>
<a class="target"> </a>
</body>
</html>
Javascript
function MouseDown(event){
event.preventDefault();
const el = event.target;
const classList = el.classList;
if( !classList.contains("hold")){
const mouseX = event.clientX;
const mouseY = event.clientY;
const targetPos = el.getBoundingClientRect();
const targetX = targetPos.x;
const targetY = targetPos.y;
/*타겟의 left, top이 그저 마우스의 좌표로 이동하게 된다면 어떻게 될지 상상해보라.*/
const gapX = mouseX - targetX;
const gapY = mouseY - targetY;
el.setAttribute("gap-x", gapX);
el.setAttribute("gap-y", gapY);
/*수많은 target 중 클릭의 타겟이 된 하나의 target에 hold 클라스 부여함*/
classList.add("hold");
}
}
function MouseMove(event){
event.preventDefault();
const el = document.querySelector(".target.hold");
if( el ){
const mouseX = event.clientX;
const mouseY = event.clientY;
const gapX = el.getAttribute("gap-x");
const gapY = el.getAttribute("gap-y");
const targetX = mouseX - gapX;
const targetY = mouseY - gapY;
el.style.left = targetX+"px";
el.style.top = targetY+"px";
}
}
function MouseUp(event){
event.preventDefault();
const el = document.querySelector(".target.hold");
el.removeAttribute("gap-x");
el.removeAttribute("gap-y");
el.classList.remove("hold");
}
$(document).ready(function(){
const targets = document.querySelectorAll(".target");
targets.forEach(function(target, idx){
target.addEventListener('mousedown', MouseDown);
});
document.addEventListener('mousemove', MouseMove);
document.addEventListener('mouseup', MouseUp);
});
'Front-end' 카테고리의 다른 글
CSS 방법론 - BEM: 클래스 작명 규칙 (0) | 2021.04.18 |
---|