JS示例37-鼠标拖拽
2019-04-06 本文已影响0人
微小码
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1 {
width: 200px;
height: 200px;
background: red;
position: absolute;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var disX = 0;
var disY = 0;
oDiv.onmousedown = function (ev) { // 鼠标按下
var oEvent = ev || event;
disX = oEvent.clientX - oDiv.offsetLeft; // 横向距离 = 鼠标位置 - div位置
disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function (ev) { // 鼠标移动(事件加到document)
var oEvent = ev || event;
oDiv.style.left = oEvent.clientX - disX + 'px';
oDiv.style.top = oEvent.clientY - disY + 'px';
};
document.onmouseup = function () { // 鼠标抬起(事件加到document)
document.onmousemove = null; // 关闭移动事件
document.onmouseup = null; // 关闭抬起事件
};
};
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>