第一種:
獲取滑鼠距離盒子上方以及左方的距離:var disX = e.clientX-oBox.offsetLeft; 最後移動的位置為:滑鼠距離瀏覽器的距離減去到盒子邊緣的距離var left = e.clientX - disX;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background: red;
position: absolute;
left: 300px;
top: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var oBox = document.getElementsByClassName("box")[0];
//滑鼠事件 down move up
oBox.addEventListener('mousedown',function(e){
console.log(e,oBox.offsetLeft,oBox.offsetTop)
var disX = e.clientX-oBox.offsetLeft;
var disY = e.clientY -oBox.offsetTop;
oBox.addEventListener('mousemove',function(e){
var left = e.clientX - disX;
var top = e.clientY - disY;
// console.log(e)
oBox.style.left = left +'px';
oBox.style.top = top + 'px';
});
oBox.addEventListener('mouseup',function(){
document.onmousemove = null;
});
});
</script>
</body>
</html>
複製程式碼
第二種:
移動後到瀏覽器頂部和左邊的距離,減去移動前到瀏覽器上方和左邊的距離。
<!-- 第二種方式 -->
<!DOCTYPE html>
<html lang="zh">
<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>拖綴</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background:blue;
position: absolute;
left: 300px;
top: 100px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var oBox = document.getElementsByClassName("box")[0];
//滑鼠事件 down move up
oBox.addEventListener('mousedown',function(e){
var lastX= e.clientX;
var lastY = e.clientY;
document.onmousemove = function(e){
var nowX = e.clientX;
var nowY = e.clientY;
var disX = nowX - lastX;
var disY = nowY - lastY;
oBox.style.left = oBox.offsetLeft + disX + 'px';
oBox.style.top = oBox.offsetTop + disY + 'px';
lastX = nowX;
lastY = nowY;
}
console.log(e,oBox.offsetLeft,oBox.offsetTop)
oBox.addEventListener('mousemove',function(e){
});
oBox.addEventListener('mouseup',function(){
document.onmousemove = null;
});
});
</script>
</body>
</html>
複製程式碼