<!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>
<script src="jquery-1.9.1.min.js"></script>
<style>
ul,li{position:relative}
li{width:100px;height:100px;float:left;list-style:none;background:#f00;display:flex;justify-content:center;align-items:center;font-size:24px;color:#fff;}
</style>
<style type="text/css">
div#computerMove{
position:absolute;
top:50px;
left:50px;
width:200px;
height:30px;
line-height:30px;
background-color:#00CCCC;
text-align:center;
color:#FFFFFF;
cursor:default;
}
</style>
</head>
<body>
<div id="computerMove">点击我拖动</div>
<script type="text/javascript">
$(document).ready(function(){
var $div = $("div#computerMove");
/* 绑定鼠标左键按住事件 */
$div.on("mousedown",function(event){
/* 获取需要拖动节点的坐标 */
var offset_x = $(this)[0].offsetLeft;//x坐标
var offset_y = $(this)[0].offsetTop;//y坐标
/* 获取当前鼠标的坐标 */
var mouse_x = event.pageX;
var mouse_y = event.pageY;
/* 绑定拖动事件 */
/* 由于拖动时,可能鼠标会移出元素,所以应该使用全局(document)元素 */
$(document).on("mousemove",function(ev){
/* 计算鼠标移动了的位置 */
var _x = ev.pageX - mouse_x;
var _y = ev.pageY - mouse_y;
/* 设置移动后的元素坐标 */
var now_x = (offset_x + _x ) + "px";
var now_y = (offset_y + _y ) + "px";
/* 改变目标元素的位置 */
$div.css({
top:now_y,
left:now_x
});
});
});
/* 当鼠标左键松开,接触事件绑定 */
$(document).on("mouseup",function(){
$(this).off("mousemove");
});
})
</script>
</body>
</html>