Vue Baidu home page my concern in dragging div is how to achieve?
div
divcss
when dragging to the middle left, there is also a dotted frame on the left, and when you let go, the dragged div is docked on the left.
if you drag to the middle right, the dragged div will dock to the right when you let go.
[if my description is not detailed enough, you can open the Baidu home page and check it after logging in to the Baidu account]
this complicated process, how is it realized, ladies and gentlemen?
this has nothing to do with the mvvm framework like vue, which is to add some view-layer logic to the native drag-and-drop events provided by the browser, which is what you want to know, right?
first of all, let's briefly talk about what the elements you see are actually:
- an imaginary box is actually a placeholder element, which is generally called
placeholder
. It may be a div, followed by a virtual box, and that's all
- the one you drag is a mirror element, which is generally called
mirror
, it may also be a div or something, and then add a drag effect style
first put these two elements on the page and hide them at the same time.
then use the browser's drag event (drag, dragStart, dragOver, which can be checked on MDN for details, to abstract the drag process, for example, from right to left:
- at the beginning of the drag event on the right, hide the element you want to drag and display mirror
The process of dragging after - will dynamically move the location of the mirror in response to the event of mouse movement
- then hovers on the container element on the left and responds to the dragOver event, which displays placeholder
in the left box.
- when the drag and drop is complete, it triggers drop-related events, hides mirror and placeholder, and moves the real right element to the left
my description is biased towards the dom layer. If you do it with vue, you can abstract the logic of the moving elements to the data layer.
but then again, this kind of drag-and-drop is actually a relatively common interaction, so there are a large number of off-the-shelf toollibraries, and I recommend a draggable . If you are interested, you can take a look at the source code of these libraries, which is basically similar to what I described above, except that the events that implement the drag-and-drop process may not be simulated by mouse events such as drag/drop, but by mouse events such as mouseup/mouseover/mousedown, but they are more or less the same.
at the same time, the whole process of dragging is an event-driven business scenario, so it would be better to use some responsive aids, such as rxjs, dealing with multiple asynchronous events at the same time.