<!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>
#box1 {
width: 100px;
height: 100px;
background-color: #bfa;
position: absolute;
}
#box2 {
width: 100px;
height: 100px;
background-color: yellow;
position: absolute;
left: 200px;
top: 200px;
}
</style>
<script>
window.onload = function () {
/*
拖拽box1元素
- 分析拖拽的流程
1、当鼠标在被拖拽元素上按下时,开始拖拽(onmousedown)
2、当鼠标移动时被拖拽元素跟随鼠标移动(onmousemove)
3、当鼠标松开时,被拖拽元素固定在当前位置(onmouseup)
*/
//获取box1
var box1 = document.getElementById("box1")
//为box1绑定鼠标按下事件
// 1、当鼠标在被拖拽元素上按下时,开始拖拽(onmousedown)
box1.onmousedown = function (event) {
event = event || window.event
//求出div的偏移量,鼠标.clentX - 元素.offsetLeft
var ol = event.clientX - box1.offsetLeft
//求出div的偏移量,鼠标.clentY - 元素.offsetTop
var ot = event.clientY - box1.offsetTop
// 2、当鼠标移动时被拖拽元素跟随鼠标移动(onmousemove)
//为document来绑定onmousemove事件
document.onmousemove = function (event) {
event = event || window.event
// 3、当鼠标松开时,被拖拽元素固定在当前位置(onmouseup)
//获取鼠标的坐标
var left = event.clientX - ol
var top = event.clientY - ot
//修改box1的位置
box1.style.left = left + "px"
box1.style.top = top + "px"
}
//为元素绑定一个鼠标松开事件
document.onmouseup = function () {
//3、当鼠标松开时,被拖拽元素固定在当前位置(onmouseup)
//取消onmousemove事件
document.onmousemove = null
//取消onmouseup事件
document.onmouseup = null
// alert("鼠标松开了")
}
}
}
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
DOM拖拽事件源码
最新推荐文章于 2023-07-26 11:14:07 发布