The js code implements a random drag overlay between several different div boxes

user:visitors Date:2021-09-28 17:13:561457

This article briefly describes how to use the js code to implement the effect of dragging the div tag in a Web page.

The code is as follows:

CSS section:

<style type="text/css">  

#divBox1, #divBox2  

{float:left; width:100px; height:35px; margin:10px;padding:10px;border:1px solid #aaaaaa;}  

</style>

js section:

For a more concise code, first refer to the jquery plug-in

<script src="jquery.js"></script>

<script type="text/javascript">  

function tuodong(ev){  

ev.preventDefault();  

}  

var srcdiv = null;  

function div_drag(ev,divdom){

srcdiv=divdom;

ev.dataTransfer.setData("text/html",divdom.innerHTML);  

function drop(ev,divdom){  

ev.preventDefault();  

if(srcdiv != divdom){  

srcdiv.innerHTML = divdom.innerHTML;  

divdom.innerHTML=ev.dataTransfer.getData("text/html");  

}  

}  

</script>  

html section:

<div id="divBox1" οndrοp="drop(event,this)" draggable="true" οndragstart="div_drag(event, this)" οndragοver="tuodong(event)">  

<p>div box 1!</p>  

</div>  

<div id="divBox2" οndrοp="drop(event,this)" draggable="true" οndragstart="div_drag(event, this)" οndragοver="tuodong(event)">  

<p>div box 2!</p>  

</div>  

Then organize the code, save it in html format with Notepad or dw, and then open the browser to quickly see the drag overlay of the div element.

The principle is also relatively simple mainly used in js ondrop, ondragover, dragable, ondragstart properties.

dragable: Allows elements to be dragged

ondrop: Drag to the specified coordinates and drop the processing that needs to be performed, where we customize the drop function to swap the two elements

ondragover: When dragging elements with default events, such as links, block the default event with ev.preventDefault() in the ondragover event. Otherwise, the drop event does not trigger.

ondragstart: Pick the processing to do with the drag target, save the drag target innerHTML here.

The above is the js code simple implementation of the drag effect between div elements.

Popular articles
latest article