简体   繁体   English

为什么我的代码不起作用?

[英]Why my code isnt working?

I have a button. 我有一个按钮。 You can appendChild a draggable div, but it doesn't work. 您可以将appendChild为可拖动的div,但是它不起作用。 Can anybody help me please? 有人可以帮我吗?

JSFiddle: https://jsfiddle.net/no2o9vo4/1/ 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. 我猜您将不得不在mousedown上选择目标,然后为mousemove添加一个事件侦听器,随着鼠标移动来更改目标的坐标,并在触发mouseup时停止监听mousemove事件。

I made a quick demo of my point here: https://jsfiddle.net/ymqycx0e/ 我在这里做了一个简短的演示: https : //jsfiddle.net/ymqycx0e/

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM