1. Pure HTML+CSS+JS implementation;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div > <div class="dialog-header">Pop-up box title</div> <div class="dialog-content">Pop-up content</div> </div> </body> <style> #draggableDialog { position: absolute; width: 300px; height: 200px; background-color: #fff; border: 1px solid #ccc; padding: 10px; } .dialog-header { cursor: move; background-color: #f0f0f0; padding: 5px; } </style> <script> const dialog = ('draggableDialog'); const dialogHeader = ('.dialog-header'); let isDragging = false; let offsetX, offsetY; ('mousedown', (e) => { isDragging = true; offsetX = - ; offsetY = - ; }); ('mousemove', (e) => { if (isDragging) { = - offsetX + 'px'; = - offsetY + 'px'; } }); ('mouseup', () => { isDragging = false; }); </script> </html>
Implementation principle: Use js event monitoring to listen to the mouse movement event of the document global DOM. When the event is triggered, the target element will shift (move) the corresponding distance with the mouse; because the target element does not always need to follow the mouse, it is specified by specifying an area for the target element.
dialogHeader
Add mouse button to match eventisDragging
Control valve to achieve the effect of dragging the target element only when the mouse is pressed in the specified area.
2. VUE template implementation;
<template> <div ref="dialog"> <div class="dialog-header" @mousedown="startDrag($event)">Pop-up box title</div> <div class="dialog-content">Pop-up content</div> </div> </template> <script> export default { data() { return { isDragging: false, offsetX: 0, offsetY: 0 }; }, methods: { startDrag(event) { = true; = - this.$; = - this.$; ('mousemove', ); ('mouseup', ); }, drag(event) { if () { this.$ = - + 'px'; this.$ = - + 'px'; } }, stopDrag() { = false; ('mousemove', ); ('mouseup', ); } } }; </script> <style> #draggableDialog { position: absolute; width: 300px; height: 200px; background-color: #fff; border: 1px solid #ccc; padding: 10px; } .dialog-header { cursor: move; background-color: #f0f0f0; padding: 5px; } </style>
The principle is the same as above;
3. Implementation of VUE global instruction;
('drag', { bind(el) { = function(e) { let disX = - ; let disY = - ; = function(e) { let left = - disX; let top = - disY; if (left < 0) left = 0; if (top < 0) top = 0; if (left > - ) left = - ; if (top > - ) top = - ; = left + 'px'; = top + 'px'; }; = function() { = null; = null; }; }; } });
Summarize
This is the article about three ways to implement interface element drag function in front-end. For more related contents for interface element drag and drop in front-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!