2012-08-16 11 views
9

Como se puede ver aquí: http://jsfiddle.net/rA4CB/6/jQueryUI lanzables, detener la propagación de los hermanos solapada

Cuando hago la caída en el área superpuesta se recibe en ambos droppables, codicioso no funciona cuando los artículos son hermanos. ¿Hay alguna forma de bloquear la recepción en los droppables inferiores en zIndex?

BTW, mouseOver no se activará para el elemento que se puede quitar ya que el mouse está realmente sobre el elemento que se puede arrastrar.

JS relevantes:

$(function() { 
    $("#draggable").draggable(); 
    $("#droppable").droppable({ 
     tolerance:'pointer', 
     drop: function(event, ui) { 
      $(this) 
       .addClass("ui-state-highlight") 
       .find("p") 
        .html("Dropped!"); 
     } 
    }); 
    $("#droppable2").droppable({ 
     tolerance:'pointer', 
     greedy:true, 
     drop: function(event, ui) { 
      $(this) 
       .addClass("ui-state-highlight") 
       .find("p") 
        .html("Dropped!"); 
     } 
    }); 
}); 

Respuesta

13

bien, así que pasar una hora tratando de averiguarlo, entonces tan pronto como te pido que luego encontrar mi respuesta

http://jsfiddle.net/rA4CB/7/

Modificado el JS a lo siguiente:

$(function() { 
    $("#draggable").draggable(); 
    $("#droppable").droppable({ 
     tolerance:'pointer', 
     drop: function(event, ui) { 
      $(this) 
       .addClass("ui-state-highlight") 
       .find("p") 
        .html("Dropped!"); 
     } 
    }); 
    $("#droppable2").droppable({ 
     tolerance:'pointer', 
     greedy:true, 
     drop: function(event, ui) { 
      $(this) 
       .addClass("ui-state-highlight") 
       .find("p") 
        .html("Dropped!"); 
     }, 
     over: function(event, ui){ 
      $("#droppable").droppable("disable") 
     }, 
     out: function(event, ui){ 
      $("#droppable").droppable("enable") 
     } 
    }); 
}); 
+1

Clever - Me tomó un tiempo para ver lo que hizo allí :-). El over/disable y out/enable es un ganador. Gracias – Matt

+0

Buen truco, pero no funciona para el número de hermanos. Así que mira mi respuesta anterior para este problema. –

+0

¿Tiene alguna idea de cómo hacer que el área solapada no se pueda quitar? –

0

Me parece que el uso # método de invertedSpear provocará el cambio de estado de interfaz de usuario que no es deseable en algunos casos. Aquí está el código.

var lastOpertion = new Date().getTime(); 

drop: function (event, ui) { 
     if (new Date().getTime() - lastOpertion < 100) return; 
     lastOpertion = new Date().getTime(); 
     .... 
} 
2

Si usted tiene un número de lanzables en una zona de contenedores entonces qué ????

Debe volver a pensar para ese problema. codicioso funciona solo para relación padre a hijo no en hermanos. Por lo tanto, debe editar los jS desplegables o poner su propia lógica para ello.

Así que si usted tiene un número de lanzables, entonces debe escribir algo de código adicional para manejar caer en perfecta lanzables, ya que es en este ejemplo A number of siblings droppables

Para hacer perfectos hermanos lanzables modificar droppbale de la siguiente

 var topElement = undefined; 
     var topElementArray = Array(); 

     $("#draggable").draggable(); 
     $(".droppableBox").droppable({ 
      activeClass: "active-droppable", 
      tolerance:'pointer', 
      over: function(event, ui) { 
       // This is for only show a message that z-index must be required for proppable 
       // you can remove it after testing or after development 
       if ($(this).css("z-index") == 'auto') { 
        alert("Please provide z-index for every droppable."); 
        return; 
       } 
       // 

       topElement = undefined; 
       topElementArray = Array(); 
       // Change it as you want to write in your code 
       // For Container id or for your specific class for droppable or for both 
       $('#demo > .droppableBox').each(function(){      
        _left = $(this).offset().left, _right = $(this).offset().left + $(this).width(); 
        _top = $(this).offset().top, _bottom = $(this).offset().top + $(this).height(); 
        if (event.pageX >= _left && event.pageX <= _right && event.pageY >= _top && event.pageY <= _bottom) { 
          topElementArray.push($(this).attr('id')); 
        } 
       }); 
      }, 
      drop: function(event, ui) { 
       if (!topElement) { 
        topElement = determineTopElement(topElementArray); 
       }     
       if ($(this).attr('id') == $(topElement).attr('id')) { 
        $(this).addClass("ui-state-highlight").find("p").html("Dropped!"); 
        // Your code after successful dropped element on specific siblings 
        // Start writing code for dropped element & perfect droppable 
       } 

      } 
     }); 

     determineTopElement = function(_array) { 
      var topElement; 
      var zIndexHighest = 0; 
      for (i = 0; i < _array.length; i++){ 
       var element = $("#"+ _array[i]); 
       var z_index = $(element).css("z-index"); 
       if(z_index > zIndexHighest){ 
        zIndexHighest = z_index; 
        topElement = element; 
       } 
      } 
      return topElement;  
     } 
+0

¿Tiene alguna idea de cómo hacer que el área solapada no se pueda quitar? –

1

En ciertas circonstances:

myjQuery.droppable({ 
    over:function(evt,ui){ 
    ui.draggable.attr('drg_time', this.drg_time = evt.timeStamp) 
    }, 
    accept:function(draggeds){ 
    if(draggeds.attr('drg_time')) 
    { 
     return draggeds.attr('drg_time') == this.drg_time 
    } 
    return draggeds.hasClass('acceptable_classes_here') 
    }, 
    out:function(evt,ui){ 
    // useless but cleaner 
    ui.draggable.removeAttr('drg_time') 
    } 
    drop:..., 
}) 
-1

prueba la opción codiciosa en ui dropable. consulte el enlace de abajo para violín de demostración:

http://jsfiddle.net/creators_guru/3vT5C/embedded/result/

$(".circles").droppable({ 
    greedy: true, 
    drop: function(event, ui) { 
     $_data = ('drgged class = ' + ui.draggable.attr('class')); 
     $_data1 = ('droped id = #' + $(this).attr('id')); 
     $('#data').html($_data + '<br/>'+$_data1); 
     return false; 
    } 
}); 
+1

Justo en mi pregunta, señalé "codicioso no funciona cuando los artículos son hermanos" – invertedSpear

5
$("#droppable").droppable({ 
    greedy: true, 
    drop: function(event, ui) { 
     if(ui.helper.is(".dropped")) { 
      return false; 
     } 
     ui.helper.addClass(".dropped"); 
    } 
}); 

acaba de establecer una clase css en ui.helper de arrastrable. Si el elemento arrastrable se ha aceptado una vez, será rechazado por todos los demás elementos que se pueden eliminar (también se puede hacer con el parámetro "aceptar" desplegable, como accept : ":not(.dropped)" y la clase agregada a ui.draggable).

+0

esto debe ser aceptado. El único problema es que necesita eliminar el período de la llamada addClass: addClass ("dropped"); Utilicé el nombre de clase "aceptado". lo único que funciona bien. –

+1

Eliminar la clase 'dropped' en' activate' también permitirá que se arrastre de nuevo. –

+0

Esto funciona muy bien si usas 'helper: "clone" 'en el archivo arrastrable, pero si es el predeterminado (que es' "original" '), entonces el arrastrable siempre se marcará como" caído "y no funcionará más . –

0

Así, al tratar de encontrar una solución sencilla que se me ocurrió esto (y que funciona para mí):

  window.overNowOnThis = ""; 
      window.olderOnes = []; 
      $obj.droppable({ 
       accept: ".draggable_imgs", 
       drop: function(e, ui) { 
        if(window.overNowOnThis == this){ 
         // Do whatever 
        } 
       }, 
       over: function(event, ui){ 
        window.olderOnes.push(window.overNowOnThis); 
        window.overNowOnThis = this; 
       }, 
       out: function(){ 
        var lastElem = window.olderOnes.pop(); 
        window.overNowOnThis = lastElem; 
       } 
      }); 

elemento superior sería seleccionado porque en él "sobre" dispara el último. Además, si hay más de dos hermanos, cuando salimos del elemento establecemos el último como actual. El uso de "ventana" global fue, por ejemplo. Una mejor opción sería usar clases, ya que puede guardar datos de forma segura.

0

Es muy similar a invertedSpear answer. Tuve que cambiar un poco debido a la activación/desactivación dentro "sobre"/"fuera" no funcionó para mí .I tenía que hacer a continuación en lugar

$("#droppable2").droppable({ 
    greedy: true, 
    drop: function (event, ui) { 
     $("droppable").droppable("disable"); 
    } 
} 

tuviera que activar de forma explícita "lanzables" cuando div Lo necesitaba. Por ejemplo, habilítelo al iniciar el evento de arrastre. Por ejemplo

$("#drageMe").draggable({ 
start:function(event,ui){ 
    $("droppable").droppable("enable"); 

}} )

Cuestiones relacionadas