2010-10-23 6 views
12

Dando dos puntos en una página web y un conjunto de elementos DOM, ¿cómo encontrar el subconjunto de esos elementos DOM que se encuentran dentro del área del rectángulo definida por los dos puntos?Obtener elementos DOM dentro de un área rectangular de una página

Estoy trabajando en una galería web, en la que cada foto está envuelta en una etiqueta li. Cuando un usuario arrastra un área de rectángulo con el mouse, todos los elementos li dentro del rectángulo se marcan como seleccionados.

Prefiere una solución jQuery para menos palabras y una forma eficiente.

Respuesta

7

intentar algo como esto:

// 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

Gracias ArtBIT. Acabo de buscar por un tiempo en Google. Parece que no hay una forma conveniente de hacer esto, no hay mejor solución que no sea repetir todos los elementos DOM y hacer matemáticas en la escuela primaria. – powerboy

+0

No te preocupes @powerboy, y sí, es por eso que agregué el soporte 'selector', para reducir la cantidad de elementos que necesitarías procesar. – ArtBIT

+0

Puede usar [getBoundingClientRect()] (https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) para obtener un objeto con 'top',' right', 'bottom' , 'left',' width' y 'height', en una llamada. –

Cuestiones relacionadas