I have a button. You can appendChild
a draggable div, but it doesn't work. Can anybody help me please?
JSFiddle: https://jsfiddle.net/no2o9vo4/1/
var diva = document.getElementById("div-a"); function adddiv() { var newdiv = document.createElement("div"); newdiv.className = "babydiv"; diva.appendChild(newdiv); } function divMove(e){ this.style.top = e.clientY + 'px'; this.style.left = e.clientX + 'px'; }
* { padding: 0; margin: 0; } #div-a { position: relative; width: 300px; height: 300px; background-color: red; } .babydiv { transform: translate(-50%, -50%); position: relative; width: 300px; height: 200px; background-color: blue; }
<div id="div-a"> <div class="babydiv" onmousedown="divMove();"> </div> </div> <a onclick="adddiv()">add div</a>
Wouldnt using the coordinates of the event only represent the coordinates when the event (mousedown) happened? Meaning you cant move it.
I guess you would have to have something select the target on mousedown
, and then add an event listener for mousemove
, changing the coordinates of the target as the mouse moves, and stop listening for the mousemove event when mouseup
is fired.
I made a quick demo of my point here: https://jsfiddle.net/ymqycx0e/
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.