<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 400px;
top: 300px;
}
</style>
<script type="text/javascript">
//鼠标按下
//跟随移动
//鼠标松开
window.onload = function() {
var box = document.getElementById("box");
box.onmousedown = function(event) {
event = event || window.event;
var ol = event.clientX - box.offsetLeft;
var ot = event.clientY - box.offsetTop;
document.onmousemove = function(event) {
event = event || window.event;
var left = event.clientX - ol;
var top = event.clientY - ot;
box.style.left = left + "px";
box.style.top = top + "px";
};
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="box"></div>
<!-- <div id="box2"></div> -->
</body>
</html>
鼠标拖拽功能
于 2022-05-25 16:56:11 首次发布