JS拖拽div(移動)
#dv {
width:100px;
height:100px;
background-color:blue;
border-radius:50%;
position:absolute;
}
<div id="dv"></div>
//獲取元素
var dv = document.getElementById('dv');
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
//滑鼠按下事件
dv.onmousedown = function(e) {
//獲取x座標和y座標
x = e.clientX;
y = e.clientY;
//獲取左部和頂部的偏移量
l = dv.offsetLeft;
t = dv.offsetTop;
//開關開啟
isDown = true;
//設定樣式
dv.style.cursor = 'move';
}
//滑鼠移動
window.onmousemove = function(e) {
if (isDown == false) {
return;
}
//獲取x和y
var nx = e.clientX;
var ny = e.clientY;
//計算移動後的左偏移量和頂部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
dv.style.left = nl + 'px';
dv.style.top = nt + 'px';
}
//滑鼠擡起事件
dv.onmouseup = function() {
//開關關閉
isDown = false;
dv.style.cursor = 'default';
}