//获取盒子
var div = document.querySelector("div");
//给div盒子添加鼠标按下事件
div.onmousedown = function (e) {
e = e || window.event;
var currentX = e.offsetX;
var currentY = e.offsetY;
//给div盒子添加鼠标移动事件
document.onmousemove = function (e) {
e = e || window.event;
var targetX = e.pageX - currentX;
var targetY = e.pageY -currentY;
div.style.left = targetX + "px";
div.style.top = targetY + "px";
}
document.onmouseup = function(e){
document.onmouseup = document.onmousemove = false;
}
}
首先获取盒子的位置,用 var div = document.querySelector("div");
给div添加鼠标按下事件,用div.onmousedown = function(e){
}