Finding all elements within a region
If i want to find all elements that are inside a box region, what is the best way to do it as a Firefox extension? If i check all leave elements and c开发者_如何学运维all getBoundingClientRect(), it'd be too slow given that there can easily be more than 500 leaves on a page.
Any help will be appreciated. Thanks.
You can use document.elementFromPoint
and visit each fifth pixel (every fifth is much faster than visiting every single pixel), adding each found element to an array:
function getElementsInRegion(x, y, width, height) {
var elements = [],
expando = +new Date,
cx = x,
cy = y,
curEl;
height = y + height;
width = x + width;
while ((cy += 5) < height) {
cx = x;
while (cx < width) {
curEl = document.elementFromPoint(cx, cy);
if ( curEl && !curEl[expando] ) {
curEl[expando] = new Number(0);
elements.push(curEl);
cx += curEl.offsetWidth;
} else {
cx += 5;
}
}
}
return elements;
}
精彩评论