2

jqueryでマウスをドラッグするのではなく、XY座標に基づいて要素を選択するにはどうすればよいですか? ここに画像の説明を入力してください

4

1 に答える 1

3

以下に示すように、jQueryプラグインは、(部分的に)位置>=xおよび>=yにあるすべての要素を選択します。

(function($){
    $.fn.filterXY = function(x, y){
        return this.filter(function(){
            var $this = $(this),
                offset = $this.offset(),
                width = $this.width(),
                height = $this.height();
            return offset.left + width >= x
                && offset.top + height >= y;
        });
    }
})(jQuery);

例:

$("*").filterXY(0,0);
$("div").filterXY(100, 0);


更新:x1とx2の間のすべての要素をフィルタリングするプラグイン

デモ: http: //jsfiddle.net/yx4sN/7/

(function($){
    $.fn.inRangeX = function(x1, x2){
        // Accepting selectors and DOM elements
        if (typeof x1 == "string" && +x1 != x1 || x1 instanceof Element) {
            x1 = $(x1);
        }
        if (typeof x2 == "string" && +x1 != x1 || x1 instanceof Element) {
            x2 = $(x2);
        }
        // Accepting jQuery objects
        if (x1 instanceof $) {
            x1 = x1.offset().left;
        }
        if (x2 instanceof $) {
            x2 = x2.offset().left;
        }
        x1 = +x1;
        x2 = +x2;

        // Make sure that x1 < x2
        if (x1 > x2) {
            var x = x1;
            x1 = x2;
            x2 = x;
        }
        return this.filter(function(){
            var $this = $(this),
                offset = $this.offset(),
                rightSide = $this.width() + offset.left;
            return offset.left >= x1
                  && rightSide <= x2;
        });
    }
})(jQuery);
于 2011-12-10T14:24:04.547 に答える