<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ width: 100px; height: 100px; background-color: red; position: absolute; } </style> </head> <body>
<div></div>
<script> //獲取須要拖拽的元素 var divs = document.querySelector('div'); //元素的鼠標落下事件 divs.onmousedown = function(ev){ //event的兼容性 var ev = ev||event; //獲取鼠標按下的座標 var x1 = ev.clientX; var y1 = ev.clientY; //獲取元素的left,top值 var l = divs.offsetLeft; var t = divs.offsetTop; //給可視區域添加鼠標的移動事件 document.onmousemove = function(ev){ //event的兼容性 var ev = ev||event; //獲取鼠標移動時的座標 var x2 = ev.clientX; var y2 = ev.clientY; //計算出鼠標的移動距離 var x = x2-x1; var y = y2-y1; //移動的數值與元素的left,top相加,得出元素的移動的距離 var lt = y+t; var ls = x+l; //更改元素的left,top值 divs.style.top = lt+'px'; divs.style.left = ls+'px'; } //清除 document.onmouseup = function(ev){ document.onmousemove = null; } } </script> </body> </html>