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

时间:2010-10-23 01:48:39

标签: javascript jquery

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

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

首选jQuery解决方案,以减少冗长而有效的方式。

1 个答案:

答案 0 :(得分:7)

尝试这样的事情:

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