在页面的矩形区域内获取DOM元素

给定网页上的两个点和一组DOM元素,如何找出位于由两点定义的矩形区域内的DOM元素的子集?

我正在开发一个基于网络的图库,其中每张照片都包含在li标签中。 当用户使用鼠标拖出矩形区域时,矩形内的所有li元素都标记为选中。

喜欢jQuery解决方案,以减少冗长和有效的方式。

尝试这样的事情:

 // 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]); }