鼠标拖拽事件

2022-08-14 08:58:50

鼠标拖拽事件

<!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 type="text/css">

#box1 {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
}
#box2 {
    width: 100px;
    height: 100px;
    background-color: yellow;
    position: absolute;
    left: 200px;
    top: 200px;
}
    </style>
    <script type="text/javascript">
        window.onload = function(){
            var box1 = document.getElementById("box1");
            box1.onmousedown = function () {
                document.onmousemove = function (event) {
                    event = event || window.event;
                    var left = event.clientX;
                    var top = event.clientY;
                    box1.style.left = left + "px";
                    box1.style.top = top + "px";
                };
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            };
        }
    </script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
  • 作者:Simms叔叔
  • 原文链接:https://blog.csdn.net/qq_43241999/article/details/102537972
    更新时间:2022-08-14 08:58:50