1. 基本功能实现
<!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>Document</title> <style> * { margin: 0; padding: 0; } div { 200px; height: 200px; border: 1px solid red; font-size: 30px; color: #000; background-color: #ccc; } </style> </head> <body> <div> hello </div> <script> var objLeft, objTop, pointX, pointY; var flag = false; $('div').style.cssText = 'position:relative;left:0px;top:0px;'; $('div').onmousedown = function (e) { var e = e || window.e; pointX = e.clientX; pointY = e.clientY; objLeft = parseFloat($('div').style.left) - 0; objTop = parseFloat($('div').style.top) - 0; flag = true; } document.onmousemove = function (e) { var e = e || window.e; if (flag) { $('div').style.left = e.clientX - pointX + objLeft + 'px'; $('div').style.top = e.clientY - pointY + objTop + 'px'; } } document.onmouseup = function () { flag = false; } function $(select) { return document.querySelector(select); } </script> </body> </html>
1.1 另一个角度 实现拖拽
<!docType html> <html> <head> <style type="text/css"> #drag { border: 1px solid blue; width: 100px; height: 100px; position: absolute; } </style> </head> <body> <input id="x" /> <input id="y" /> <div id="drag"> <input value="x" /> <input value="y" /> </div> <script> var drag = document.getElementById('drag'); var inputX = document.getElementById('x'); var inputY = document.getElementById('y'); if (document.attachEvent) { drag.attachEvent('onmousedown', dragHandle); } else { drag.addEventListener('mousedown', dragHandle, false); } function dragHandle(event) { var event = event || window.event; var startX = drag.offsetLeft; var startY = drag.offsetTop; var mouseX = event.clientX; var mouseY = event.clientY; var deltaX = mouseX - startX; var deltaY = mouseY - startY; if (document.attachEvent) { drag.attachEvent('onmousemove', moveHandle); drag.attachEvent('onmouseup', upHandle); drag.attachEvent('onlosecapture', upHandle); drag.setCapture(); } else { document.addEventListener('mousemove', moveHandle, true); document.addEventListener('mouseup', upHandle, true); } function moveHandle(event) { var event = event || window.event; drag.style.left = (event.clientX - deltaX) + "px"; drag.style.top = (event.clientY - deltaY) + "px"; inputX.value = drag.style.left; inputY.value = drag.style.top; } function upHandle() { if (document.attachEvent) { drag.detachEvent('onmousemove', moveHandle); drag.detachEvent('onmouseup', upHandle); drag.detachEvent('onlosecapture', upHandle); drag.releaseCapture(); } else { document.removeEventListener('mousemove', moveHandle, true); document.removeEventListener('mouseup', upHandle, true); } } } </script> </body> </html>
2.相关文章