본문 바로가기
JavaScript

[Javascript] 버튼 이동 시키기

by teamnova 2024. 4. 29.
728x90

오늘은 버튼을 드래그 하면 버튼이 이동 되도록 만들어 보겠습니다.

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>마우스 이동</title>
    <style>
        #myButton {
            position: absolute;
            top: 50px;
            left: 50px;
        }
    </style>
</head>
<body>

<button id="myButton">클릭</button>

<script>
    var button = document.getElementById('myButton');
    var isMouseDown = false;
    var initialMouseX, initialMouseY;
    var initialButtonX, initialButtonY;

    button.addEventListener('mousedown', function(event) {
        isMouseDown = true;
        initialMouseX = event.clientX;
        initialMouseY = event.clientY;
        initialButtonX = button.offsetLeft;
        initialButtonY = button.offsetTop;
    });

    document.addEventListener('mousemove', function(event) {
        if (isMouseDown) {
            var offsetX = event.clientX - initialMouseX;
            var offsetY = event.clientY - initialMouseY;
            var newButtonX = initialButtonX + offsetX;
            var newButtonY = initialButtonY + offsetY;

            button.style.left = newButtonX + 'px';
            button.style.top = newButtonY + 'px';
        }
    });

    document.addEventListener('mouseup', function() {
        isMouseDown = false;
    });
</script>

</body>
</html>

 

결과