简体   繁体   English

jQuery-检查元素是否在另一个元素之上

[英]jQuery - check if element is above another one

What is the best way to check if element is above another one? 检查元素是否在另一个元素上方的最佳方法是什么?

I have container with a lot of children with absolute position, and each of the children is draggable with jQuery-ui draggable.. 我有很多带有绝对位置的子代的容器,并且每个子代都可以用jQuery-ui draggable拖动。

I need to check in the drag stop if the dragged element is dropped above another one. 我需要检查拖动停止位置是否将拖动的元素放置在另一个元素之上。

I know I could take the element center and iterate all the other elements and check if it is in their area, but I'm looking for more elegant way to check this. 我知道我可以将元素居中并重复所有其他元素,然后检查它是否在其区域中,但是我正在寻找一种更优雅的方法来进行检查。

Check this fiddle please: http://jsfiddle.net/g36gLss9/1/ 请检查此小提琴: http : //jsfiddle.net/g36gLss9/1/

$(function() {
    $( ".draggable" ).draggable({
        stop: function( event, ui ) {
            $( ".draggable" ).each(function(obj){
                $(this).html( 'z-index: ' + $(this).css("z-index"));
            });
        },
        drag: function( ) {
            $(this).html( 'z-index while dragging: ' + $(this).css("z-index"));
        }
    });
  });

As the example demonstrates, the draggable feature from jquery ui leaves the z-index value of the dragged elements untouched. 如示例所示,jquery ui的可拖动功能使被拖动元素的z-index值保持不变。

therefore you can assume that an element appearing after another draggable item would be positioned above said item. 因此,您可以假设出现在另一个可拖动项目之后的元素将位于该项目的上方。

That might not be true though, in case you set z-index manually before. 但是,如果您之前手动设置了z-index,那可能就不正确了。 Bu the example also states how to retrieve the z-index of a draggable item. 该示例还说明了如何检索可拖动项目的z-index。 So to be on the safe side you could compae values for z-index first. 为了安全起见,您可以先比较z-index的值。 and in case of equality compare the order of appearance in the code. 并在相等的情况下比较代码中的出现顺序。

Also you can hande the z-index of draggable items with the zIndex option documented here: http://api.jqueryui.com/draggable/#option-zIndex 您也可以使用此处记录的zIndex选项来处理可拖动项的z-index: http ://api.jqueryui.com/draggable/#option-zIndex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM