直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
/* width: 50px;
height: 50px; */
/* background: red; */
position: relative;
color: green;
font-size: 50px;
float: left;
}
div:hover {
color: black;
}
</style>
<script src="jquery-1.10.2.js"></script>
</head>
<body>
<div class="div1">❤</div>
</body>
<script>
// 在页面上拖拽一个div盒子 用到的事件
// mousedown up move
$('.div1').mousedown(function (e) {
// 鼠标按下后就要取到当前元素的x、y的位置数据
var x = e.pageX;
var y = e.pageY;
// 取到了x和y的坐标对象
var divx = $(this).offset().left;
var divy = $(this).offset().top;
// 绑定一个鼠标移动的事件
$(document).bind('mousemove', function (event) {
// 鼠标移动时 取当前移动后的x、y的数据
var x2 = event.pageX;
var y2 = event.pageY;
// 根据移动后的x和y的数据 和起点的数据做比较 最后给对象元素设置位置
$('.div1').css({
top: divy + (y2 - y) + 'px',
left: divx + (x2 - x) + "px"
});
})
});
// 当鼠标按钮抬起 放开的时候 把鼠标移动事件移除
$('.div1').mouseup(function () {
$(document).unbind('mousemove');
});
</script>
</html>