Draggable et divs superposées
by daggoon
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="content">
<div class="blocPhoto">
<div class="visuel">
<img id="upload" src="https://blog-fr.orson.io/wp-content/uploads/2017/06/jpeg-ou-png.jpg">
</div>
<img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" id="logo">
</div>
</div>
<script src="js/draggable.js"></script>
</body>
</html>
CSS
.content {
width:100%;
height:920px;
justify-content: center;
align-items: center;
display: flex;
background-color:#dfe1e6;
}
.blocPhoto {
width:1000px;
height:700px;
position:relative;
}
.visuel {
width:1000px;
height:563px;
overflow: hidden;
background-color:grey;
position: absolute;
}
#upload {
width:1020px;
position: relative;
}
#logo {
position: absolute;
width:250px;
margin-left:730px;
margin-top: 20px;
}
JavaScript
dragElement(document.getElementById("upload"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
/* if present, the header is where you move the DIV from:*/
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
/* otherwise, move the DIV from anywhere inside the DIV:*/
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}