<!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>拖拽</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload = function(){
var box = document.getElementById("box");
box.onmousedown = function(event){
//控制鼠标光标
event = event||window.event;
//div的偏移量:鼠标的位置 - 元素的位置
var ml = event.clientX - box.offsetLeft;
var mt = event.clientY - box.offsetTop;
document.onmousemove = function(event){
event = event||window.event;
var x = event.clientX;
var y = event.clientY;
box.style.left = x-ml+"px";
box.style.top = y-mt+"px";
//注意一定要在上面样式加定位
};
document.onmouseup = function(){
//鼠标松开,取消移动事件
document.onmousemove = null;
//取消当前事件
document.onmouseup = null;
}
}
}
</script>
</body>
</html>
JS-拖拽
最新推荐文章于 2024-05-09 13:57:56 发布