<!DOCTYPE HTML>
<html>
<head>
<title>offset案例:鼠标拖动盒子移动</title>
<meta charset="utf-8" />
<style>
* {
margin: 0;
padding: 0;
}
#box {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
cursor: move;
}
</style>
</head>
<body>
<div id="box"> </div>
<script>
//鼠标按下触发 mousedown 鼠标移动 mousemove 鼠标松开 mouseup
var box = document.getElementById('box');
//鼠标按下 有一个坐标
/*var x2 = null;
var y2 = null;
var x1 = null;
var y1 = null;*/
box.addEventListener('mousedown', function(e) {
//先算出鼠标按下时,鼠标在盒子内的坐标
var x1 = e.pageX - box.offsetLeft;
var y1 = e.pageY - box.offsetTop;
//console.log(x1 +','+ y1);
//鼠标移动后的坐标减去鼠标在盒子内的坐标,就是盒子的坐标了
document.addEventListener('mousemove', move)
function move(e) {
var x2 = e.pageX - x1;
var y2 = e.pageY - y1;
//console.log(x2 +','+ y2);
box.style.left = x2 + 'px';
box.style.top = y2 + 'px';
}
//鼠标松开 移除移动事件,让盒子不再跟着鼠标走了
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove',move);
})
})
</script>
</body>
</html>
offset案例:鼠标拖动盒子移动,鼠标松开后 盒子不再跟鼠标移动
猜你喜欢
转载自blog.csdn.net/tuzi007a/article/details/105452240
今日推荐
周排行