In the web page, you need to change the position of multiple elements, which can be achieved by dragging the element. A global attribute draggable is added to HTML5, which controls whether the element can be dragged by setting true/false.
Let’s take picture drag as an example and use jQuery to implement it: there are multiple pictures on the page, drag one picture to the middle of the other two pictures, and then the position of this picture can be inserted between the two pictures.
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<style>
.img-div img {
width:200px;
height:200px;
float: left;
}
.img-div {
float: left;
}
.drop-left,.drop-right {
width: 50px;
height: 200px;
float: left;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Parent DIV of the dragged image
var $srcImgDiv = null;
// Start dragging
$(".img-div img").bind("dragstart", function() {
$srcImgDiv = $(this).parent();
});
// Events fired when dragging above .drop-left, .drop-right
$(".drop-left,.drop-right").bind("dragover", function(event) {
// Allow drag and drop must be set through event.preventDefault()
event.preventDefault();
});
// End the event of dragging and releasing the mouse
$(".drop-left").bind("drop", function(event) {
event.preventDefault();
if($srcImgDiv[0] != $(this).parent()[0]) {
$(this).parent().before($srcImgDiv);
}
});
$(".drop-right").bind("drop", function(event) {
event.preventDefault();
if($srcImgDiv[0] != $(this).parent()[0]) {
$(this).parent().after($srcImgDiv);
}
});
});
</script>
</head>
<body>
<div>
<div></div>
<img src="http://photos.tuchong.com/38538/f/6864556.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://photos.tuchong.com/349669/f/6695960.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://photos.tuchong.com/349669/f/6683901.jpg" draggable="true">
<div></div>
</div>
<div>
<div></div>
<img src="http://photos.tuchong.com/349669/f/5121337.jpg" draggable="true">
<div></div>
</div>
</body>
</html>
dragstart is the event that starts dragging the element, dragover is the event that drags above the element, and drop is the event that ends dragging and releases the mouse.
draggable="true" means that the img element can be dragged, but in fact, img is draggable by default, so this property can also be removed. If you want to drag the div element, you need to set draggable="true".
The div elements with class drop-left and drop-right are placed on the left and right sides of the picture, and are used to receive other pictures and drag to this position.