拖动改变div位置
2025年4月30日小于 1 分钟
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖动改变div位置</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
#move
{
width:100px;
height:100px;
border:solid 1px blue;
background:lightgreen;
border-radius:50%;
position:absolute;
left:0px;
top:0px;
}
</style>
</head>
<body>
<div id='move'></div>
<script type="text/javascript">
var move=document.getElementById('move');
//鼠标按下事件
move.onmousedown=function(e)
{
//获取当前坐标
var x=e.clientX;
var y=e.clientY;
//获取当前距可视窗口的偏移量
var l=move.offsetLeft;
var t=move.offsetTop;
//鼠标样式改为移动
move.style.cursor='move';
//鼠标移动事件
window.onmousemove=function(e)
{
//获取移动后的坐标
var xh=e.clientX;
var yh=e.clientY;
//得到新的据可视窗口的偏移量
var lh=xh-(x-l);
var th=yh-(y-t);
move.style.left=lh+'px';
move.style.top=th+'px';
}
}
//鼠标弹起事件
move.onmouseup=function()
{
window.onmousemove=null;
move.style.cursor='';
}
</script>
</body>
</html>