原生js div拖动
<!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>div拖动</title>
<style>
html,body{
padding: 0;
margin: 0;
}
.con{
width: 100px;
height:100px;
border:1px solid red;
border-radius:6px;
background-color:aquamarine;
}
</style>
</head>
<body>
<div class="con"></div>
<script>
var con = document.querySelector('.con');
var ismove = false;
var _x,_y,_Left,_Top;
con.onmousedown = function(down){
con.style.cursor = 'move'
ismove = true;
_x = down.clientX;
_y = down.clientY;
_Left = con.offsetLeft;
_Top = con.offsetTop;
}
con.onmousemove = function(move){
if(ismove){
con.style.marginLeft = move.clientX -_x + _Left +'px';
con.style.marginTop = move.clientY -_y + _Top+'px';
}
}
con.onmouseover = function(over){
_x = over.clientX;
_y = over.clientY;
con.style.cursor = 'auto'
ismove = false
}
con.onmouseup = function(up){
_x = up.clientX;
_y = up.clientY;
con.style.cursor = 'auto'
ismove = false
}
</script>
</body>
</html>