<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
*{
margin:0;
padding:0;
}
#box{
width:200px;
height:200px;
background:orange;
position:absolute;
left:100px;
top:100px;
cursor:move;
}
</style>
<body>
<div id="box">啊啊啊啊啊</div>
</body>
</html>
<script>
/*
第一步 :鼠标按下 记录鼠标相对应拖拽元素的内部偏移量
var disx = e.offsetX || e.layerX e.offsetY
或者
disx = e.pageX - div.offsetLeft; 兼容性好
第二步: 鼠标在按下时 移动,改变拖拽元素的left和top值
left : e.pageX - disx
top : e.pageY - disy
第三步 :鼠标抬起事件
抬起鼠标时 取消移动
*/
let oDiv = document.querySelector("#box");
oDiv.onmousedown = function(e){
var e = e || event;
//记录内部偏移量
let disx = e.offsetX || e.layerX;
let disy = e.offsetY || e.layerY;
//添加鼠标移动事件 (在哪移动?)
document.onmousemove = function(e){
//移动时 取消文字被选中的状态
window.getSelection().removeAllRanges();
var e = e||event;
//获取div的最大left和top值
var maxL = window.innerWidth - oDiv.offsetWidth;
var maxT = window.innerHeight - oDiv.offsetHeight;
//设置拖拽元素div的left和top值
var x = e.pageX - disx;
var y = e.pageY - disy;
//边界处理
/*if( x < 0 ){ //左边界
x = 0;
}else if( x > maxL ){ //右边界
x = maxL;
}
if( y < 0 ){ //上边界
y = 0;
}else if( y > maxT ){
y = maxT;
}*/
//边界处理
x = x < 0 ? 0 : ( x > maxL ? maxL : x );
y = y < 0 ? 0 : ( y > maxT ? maxT : y );
oDiv.style.left = x + "px";
oDiv.style.top = y + "px";
}
//鼠标抬起 取消移动(事件源??建议在document上)
document.onmouseup = function(){
//取消移动
document.onmousemove = null;
}
//return false;
}
//[{x :横坐标 , y :纵坐标 },{},{},{}]
</script>