¿Por qué se arrastran ambos cuadrados al mismo tiempo?

The following example will present a page with two draggable squares I made. Nomatter how hard I tried though, I can't figure out why both squares are being dragged at the same time when I try to drag just one.

<html>
<head>
    <title>Hello!</title>
    <script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>
</head>
<body>

<h2>Hello</h2>

<div style="border: 1px solid red; height: 300px; position: relative;" id="canvas">

    <div style="background-color: yellow; width: 100px; height: 100px; position: relative;" class="square" />
    <div style="background-color: blue; width: 100px; height: 100px; position: relative; top: 200px; left: 200px;" class="square" />

</div>

<script type="text/javascript">
var mousePointsOn;
var holdX;
var holdY;
var track = function(e) {
    mousePointsOn.css('left', e.pageX - $("#canvas").offset().left - holdX);
    mousePointsOn.css('top', e.pageY - $("#canvas").offset().top - holdY);
};
$('#canvas').delegate('.square', 'mousedown', function(e) {
    holdX = e.pageX - $(this).offset().left;
    holdY = e.pageY - $(this).offset().top;
    e.preventDefault();
    mousePointsOn = $(this);
    $('body').bind('mousemove', track);
});
$('#canvas').delegate('.square', 'mouseup', function() {
    $('body').unbind('mousemove', track);
});
</script>

</body>
</html>

Gracias por su atención.

preguntado el 01 de febrero de 12 a las 23:02

2 Respuestas

No se puede utilizar <div /> to create a div with no content. The browser has actually interpreted the first square as an unclosed div, and nested the second div, as well as the script below inside it. Use <div></div> en vez.

Respondido 02 Feb 12, 03:02

This is exactly what I was about to type out. :D - VictorKilo

Closing the <div>s solved most of my problem. But now the blue square appears in the wrong position (300px down instead of 200px), and doesn't drag properly. Any idea what I might be doing wrong? - Alexk

Yes. You're using relative positioning to adjust the squares. The blue square naturally wants to align itself directly under the yellow square. From there, you're telling it to move 200px down, and 200px to the right. Use position: absolute instead, or adjust your offsets. - zim2411

Your HTML is wrong. <div></div> need to be closed properly. Also both <div> have the square class, so the mousedown function is bound to both.

Respondido 02 Feb 12, 03:02

Ok, I fixed <div></div>. But if I want both squares to be draggable, shoudn't I bind mousedown to both? - Alexk

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.