기본 JS 마우스 누름 끌기

12807 단어 네이티브 JS

기본 JS 마우스 누름 끌기


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>    title>
    <style type="text/css">
        body {
            margin: 0;
        }

        div {
            width: 200px;
            height: 200px;
            position: absolute;
            background-color: pink;
        }
    style>
head>

<body>

    <div onmousedown="downDiv(this)" onmousemove="moveDiv(this)" onmouseup="upDiv(this)">

    div>



    <script>
        //      div   
        var obj_w, obj_h;
        //                
        var mouseDown = false;

        //      
        function downDiv(obj) {
            //  div   
            obj_w = obj.offsetWidth;
            obj_h = obj.offsetHeight;
            //  
            var e = event || window.event;
            //e.clientX/Y              ; div         
            obj.style.left = (e.clientX - obj_w / 2) + "px";
            obj.style.top = (e.clientY - obj_h / 2) + "px";
            console.log(obj.style.left, obj.style.top)
            //    ture,    false,         mouveDiv
            mouseDown = true;

        }

        //      
        function moveDiv(obj) {
            obj_w = obj.offsetWidth;
            obj_h = obj.offsetHeight;
            var e = event || window.event;
            console.log(e.clientX, e.clientY);
            console.log(obj_w, obj_h);
            if (mouseDown) {
                obj.style.left = (e.clientX - obj_w / 2) + "px";
                obj.style.top = (e.clientY - obj_h / 2) + "px";
                console.log(obj.style.left, obj.style.top)
            }

        }

        //      
        function upDiv(obj) {
            mouseDown = false;
        }

    script>
body>

html>

좋은 웹페이지 즐겨찾기