<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鼠标拖动div移动</title>
<style type="text/css">
*{margin:0px;padding:0px;}
#move{width:200px;height:200px;background:orange;font-family:microsoft yahei;position:absolute;top:200px;left:400px;}
</style>
</head>
<body>
<div id="move"></div>
<script type="text/javascript">
var move = document.getElementById('move');
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;//声明一个全局变量 用来标识当前鼠标是否按下
///绑定事件
move.onmousedown = function(e){
//获取尺寸
x = e.clientX;
y = e.clientY;
l = move.offsetLeft;
t = move.offsetTop;
//修改检测变量isDown
isDown = true;
//修改样式
move.style.cursor = 'move';
move.style.background = 'red';
}
//鼠标移动
window.onmousemove = function(e){
//进行判断
if(!isDown){
return;
}
//获取鼠标移动之后的位置
var _x = e.clientX;
var _y = e.clientY;
//计算新的left和top
var newLeft = _x - (x-l);
var newTop = _y - (y-t);
//设置新的样式(left和top)
move.style.left = newLeft + 'px';//建议大家在最后设置样式的时候再加px单位
move.style.top = newTop + 'px';
}
//鼠标抬起
move.onmouseup = function(){
//修改检测变量的值
isDown = false;
move.style.cursor = 'default';
move.style.background = 'orange';
}
</script>
</body>
</html>
鼠标拖动div移动
最新推荐文章于 2022-07-14 17:33:55 发布