<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>movemouse</title> <style> *{ margin: 0; padding: 0; } #box{ width: 200px; height: 200px; background-color: rebeccapurple; } </style> </head> <body> <div id="box" style="position: absolute;left: 0px; top: 0px;"></div> </body> <script> var box = document.getElementById("box"); var dx = 0; var dy = 0; var flag = false; box.onmousedown = function (e) { var ent = e || window.event; dx = ent.clientX - parseFloat(this.style.left); dy = ent.clientY - parseFloat(this.style.top); flag = true; } document.body.onmousemove = function (e) { if(!flag) { return; } var ent = e || window.event; box.style.left = ent.clientX - dx + "px"; box.style.top = ent.clientY - dy + "px"; } box.onmouseup = function (e) { flag = false; } box.onmouseout = function (e) { flag = false; } </script> </html>
JavaScript鼠标拖动
最新推荐文章于 2022-01-10 13:07:35 发布