2010-10-23 5 views
12

Dato due punti su una pagina Web e un set di elementi DOM, come scoprire il sottoinsieme di quegli elementi DOM che si trovano all'interno dell'area del rettangolo definita dai due punti?Ottieni elementi DOM all'interno di un'area rettangolare di una pagina

Sto lavorando a una galleria basata sul Web, in cui ogni foto è racchiusa in un tag li. Quando un utente trascina un'area del mouse con il mouse, tutti gli elementi li all'interno del rettangolo sono contrassegnati come selezionati.

Preferire una soluzione jQuery per meno prolisso ed efficiente.

risposta

7

provare qualcosa di simile:

// x1, y1 would be mouse coordinates onmousedown 
// x2, y2 would be mouse coordinates onmouseup 
// all coordinates are considered relative to the document 
function rectangleSelect(selector, x1, y1, x2, y2) { 
    var elements = []; 
    jQuery(selector).each(function() { 
     var $this = jQuery(this); 
     var offset = $this.offset(); 
     var x = offset.left; 
     var y = offset.top; 
     var w = $this.width(); 
     var h = $this.height(); 

     if (x >= x1 
      && y >= y1 
      && x + w <= x2 
      && y + h <= y2) { 
      // this element fits inside the selection rectangle 
      elements.push($this.get(0)); 
     } 
    }); 
    return elements; 
} 

// Simple test 
// Mark all li elements red if they are children of ul#list 
// and if they fall inside the rectangle with coordinates: 
// x1=0, y1=0, x2=200, y2=200 
var elements = rectangleSelect("ul#list li", 0, 0, 200, 200); 
var itm = elements.length; 
while(itm--) { 
    elements[itm].style.color = 'red'; 
    console.log(elements[itm]); 
} 
+1

Grazie ArtBIT. Ho appena cercato per un po 'su Google. Sembra che non ci sia un modo conveniente per farlo, nessuna soluzione migliore se non il looping di tutti gli elementi DOM e la matematica elementare su di essi. – powerboy

+0

Nessun problema @powerboy, e sì, è per questo che ho aggiunto il supporto 'selector', per ridurre il numero di elementi che avresti bisogno di elaborare. – ArtBIT

+0

È possibile utilizzare [getBoundingClientRect()] (https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) per ottenere un oggetto con 'top',' right', 'bottom' , 'left',' width' e 'height', in una chiamata. –

Problemi correlati