如何使用jquery基于xy坐标而不是使用鼠标拖动来选择元素?

2023-12-02

How to select elements based on XY coordinates and not with mouse drag with jquery? enter image description here


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 之间所有元素的插件

Demo: 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用jquery基于xy坐标而不是使用鼠标拖动来选择元素? 的相关文章

随机推荐