【js】js实现拖拽功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>test</title> <style> html, body { margin: 0px; padding: 0px; width: 100%; height: 100%; } div { position: absolute; } .red { top: 0px; left: 0px; width: 100px; height: 100px; background: red; } .green { top: 500px; left: 100px; width: 80px; height: 100px; background: green; } .blue { top: 200px; left: 160px; width: 180px; height: 150px; background: blue; } </style> </head> <body> <div class="red">red</div> <div class="green">green</div> <div class="blue">blue</div> <script> var div = document.getElementsByTagName('div'); // PC端实现 document.addEventListener('mousedown', function (e) { console.log('pc端'); let target = e.target; if (target.tagName == 'DIV') { let distanceX = e.clientX - target.offsetLeft; let distanceY = e.clientY - target.offsetTop; function mousemove(e) { let x = e.clientX - distanceX, y = e.clientY - distanceY, window_width = document.documentElement.clientWidth - target.offsetWidth, window_height = document.documentElement.clientHeight - target.offsetHeight; x = x < 0 ? 0 : x; // 当元素到窗口最左边 x = x > window_width ? window_width : x; // 当元素到窗口最右边 y = y < 0 ? 0 : y; // 当元素到窗口最上边 y = y > window_height ? window_height : y; // 当元素到窗口最下边 target.style.top = y + 'px'; target.style.left = x + 'px'; } document.addEventListener('mousemove', mousemove, false); function mouseup(e) { document.removeEventListener('mousemove', mousemove, false); document.removeEventListener('mouseup', mouseup, false); } document.addEventListener('mouseup', mouseup, false) } }, false) // 移动端实现 document.addEventListener('touchstart', function (e) { console.log('移动端'); let target = e.target; if (target.tagName == 'DIV') { let distanceX = e.touches[0].clientX - target.offsetLeft; let distanceY = e.touches[0].clientY - target.offsetTop; function touchmove(e) { let x = e.touches[0].clientX - distanceX, y = e.touches[0].clientY - distanceY, window_width = document.documentElement.clientWidth - target.offsetWidth, window_height = document.documentElement.clientHeight - target.offsetHeight; x = x < 0 ? 0 : x; // 当元素到窗口最左边 x = x > window_width ? window_width : x; // 当元素到窗口最右边 y = y < 0 ? 0 : y; // 当元素到窗口最上边 y = y > window_height ? window_height : y; // 当元素到窗口最下边 target.style.top = y + 'px'; target.style.left = x + 'px'; } document.addEventListener('touchmove', touchmove, false); function touchend(e) { document.removeEventListener('touchmove', touchmove, false); document.removeEventListener('touchend', touchend, false); } document.addEventListener('touchend', touchend, false); } }) </script> </body> </html>
注意:移动端和PC端事件触发稍有不同。
【参考文章】