How to select elements based on xy coordinates, not using mouse drag, with jquery?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 19:58:42

问题


How to select elements based on XY coordinates and not with mouse drag with jquery?


回答1:


The jQuery plugin, as shown below, will select all elements which are (partially) at position >= x and >= 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);

Examples:

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


Update: Plugin to filter all elements between x1 and 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);


来源:https://stackoverflow.com/questions/8457082/how-to-select-elements-based-on-xy-coordinates-not-using-mouse-drag-with-jque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!