1. 程式人生 > >js簡單的可拖動的div

js簡單的可拖動的div

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>拖動框</title>
    <style>
        #box {
            width: 300px;
            height: 200px;
            background: #f0f0f0;
            cursor: move;
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div id="box">

</div>
</body>
</html>
<script type="text/javascript">
    var isDragging = false; // 不可拖動
    var box = document.getElementById("box")
    var x = null,y = null;
    function handleEvent(event) {
        switch (event.type) {
            case 'mousedown':
                isDragging = true;
                x = event.clientX-box.offsetLeft;
                y = event.clientY-box.offsetTop;
                break;
            case 'mouseup':
                isDragging = false;
                break;
            case 'mousemove':
                if(isDragging) {
                    console.log(event.clientX)
                    // 可以進行拖動
                    box.style.left = event.clientX-x+"px";
                    box.style.top = event.clientY-y+"px";
                }
                break;
        }
    }
    box.onmousedown = handleEvent;
    box.onmousemove = handleEvent;
    box.onmouseup = handleEvent;
</script>