2010-08-24 3 views

Répondre

6

L'optimal serait de simplement envoyer un sélecteur pour les champs qui devraient contenir le confinement, mais comme cela ne fonctionnera pas j'ai tripoté avec une solution alternative. Je ne dirais pas que c'est très optimal mais je vais essayer. Trouvez les points extrêmes (à gauche, en haut, à droite, en bas) des cellules que vous êtes censé faire glisser le draggable et définissez ces points comme le confinement du draggable. Dans mon exemple, j'ai donné ces éléments (td s de la table) la classe containmentTD. Il ne prend pas en compte les frontières, padding ect, il faudra donc le peaufiner si c'est important.

//The TD elements that are to be included when 
//we find the dimentions of the containment 
var td_elements = $(".containmentTD"); 

//This will hold the extreme points of the containment 
var points = { 
    left: td_elements.eq(0).position().left, 
    top: td_elements.eq(0).position().top, 
    right: 0, 
    bottom: 0 
}; 

//Find the points of the containment 
td_elements.each(function() { 
    var t = $(this); 
    var p = t.position(); 
    var width = t.width(); 
    var height = t.height(); 

    points.left = Math.min(p.left, points.left); 
    points.top = Math.min(p.top , points.top); 
    points.right = Math.max(points.right, p.left + width); 
    points.bottom = Math.max(points.bottom, p.top + height); 
}); 

//This will only work "perfectly" when all draggables have 
//the same dimentions 
points.bottom -= $("div.draggable:first").height(); 
points.right -= $("div.draggable:first").width(); 

$("div.draggable").draggable({ 
    containment: [points.left, points.top, points.right, points.bottom] 
}); 

Voici une démo: http://jsfiddle.net/uTyTY/ Notez que le carré rouge est là que pour visualiser la zone de confinement