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

pow*_*boy 13 javascript jquery

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

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

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

Art*_*BIT 9

尝试这样的事情:

// 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]);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢ArtBIT。我刚刚在Google上搜索了一段时间。似乎没有方便的方法来执行此操作,没有比循环所有DOM元素并对它们进行小学数学更好的解决方案了。 (2认同)