用js实现div元素的拖拽、

用js来实现div元素的拖拽。

HTML代码如下。

<!DOCTYPE html>
<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>Document</title>
<style>
*{margin:0;padding: 0}
#box{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
</html>

script代码。

<script>
    var oBox = document.getElementById("box");

    oBox.onmousedown = function (e) { 
        var e = e||event;
        var disX = e.offsetX;
        var disY = e.offsetY;

        document.onmousemove = function(e){
            var e = e||event;

            var x = e.clientX - disX;
            var y = e.clientY - disY;


            oBox.style.left = x + "px";
            oBox.style.top = y + "px";
        }

        document.onmouseup = function(){
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
</script>
原文地址:https://www.cnblogs.com/-wentao/p/10697183.html