确定重叠元素顺序

时间:2013-04-23 15:57:20

标签: html5 gwt dom drag-and-drop z-index

我正在使用gwt和gwt-dnd(一个很棒的拖放库)。

我有一个与另一个重叠的dropTarget(div),并且库选择下一个用于放置操作。 原因是选择是按照以下标准完成的:

  

确定哪个DropController代表最深的DOM后代   放置位于提供位置(x, y)的目标。

适用于降序DropTargets,但不适用于这样的层次结构:

<body>
    <div id="a">
        <div id="b">
            <div id="c">
                <div id="DropTarget_D"></div>
            </div>
        </div>
    </div>
    <div id="1" style="position:absolute; z-index: 1; top:0; left:0">
         <div id="DropTarget_2"></div>
    </div>
</body>

演示:http://jsfiddle.net/rxwMB/

从代码中可以看到(在帖子的末尾),在这种情况下,即使显示DropTarget_2,也会使用DropTarget_C(因为它是“最深的”)。

如果给出两个组件,哪一个是最顶层组件,我怎么知道?

这是选择的代码:

private int compareElement(Element myElement, Element otherElement) {
  if (myElement == otherElement) {
    return 0;
  } else if (DOM.isOrHasChild(myElement, otherElement)) {
    return -1;
  } else if (DOM.isOrHasChild(otherElement, myElement)) {
    return 1;
  } else {
    // check parent ensuring global candidate sorting is correct
    Element myParentElement = myElement.getParentElement().cast();
    Element otherParentElement = otherElement.getParentElement().cast();
    if (myParentElement != null && otherParentElement != null) {
      return compareElement(myParentElement, otherParentElement);
    }
    return 0;
  }
}

dropTarget是从使用此函数排序的有序列表中选取的。 如果列表仅包含DropTarget_D和DropTarget_2且两者都符合条件,则会选择第一个(即使它被DropTarget_2覆盖)

1 个答案:

答案 0 :(得分:0)

这是我的解决方案:

(对于gwt-dnd:https://code.google.com/p/gwt-dnd/issues/detail?id=169

package com.allen_sauer.gwt.dnd.client;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.allen_sauer.gwt.dnd.client.DropControllerCollection.Candidate;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.RootPanel;

public class OverlappingDropTargetsHandler {

    private static class StackingContext{
        private Element element;
        private LinkedList<Object> childrens;

        public StackingContext(Element element) {
            if(element == null){
                throw new RuntimeException();
            }
            this.element = element;
            this.childrens = new LinkedList<Object>();
        }

        public Element getElement() {
            return element;
        }

        public void addChildren(Candidate candidate) {
            this.childrens.add(candidate);
        }

        public void addChildren(StackingContext stackingContext) {
            this.childrens.add(stackingContext);            
        }

        public LinkedList<Object> getChildrens() {
            return this.childrens;
        }

        public int getZIndex(){
            return this.element.getPropertyInt("z-index");
        }

        @Override
        public int hashCode() {
            return element.hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if(obj instanceof StackingContext){
                return this.element.equals(((StackingContext)obj).element);
            }else{
                return false;
            }
        }
    }

    public static void sort(Candidate[] candidates) {       
        HashMap<Element, OverlappingDropTargetsHandler.StackingContext> cache = new HashMap<Element, OverlappingDropTargetsHandler.StackingContext>();

        initStackingContextsList(candidates, cache);

        StackingContext rootStackingContext = resolveStackingContextsHierarcy(cache);

        cache = null; //non mi serve piu

        assert rootStackingContext != null;

        Comparator<Object> comparator = new Comparator<Object>() {
            @Override
            public int compare(Object a, Object b) {
                assert a instanceof StackingContext || a instanceof Candidate;
                assert b instanceof StackingContext || b instanceof Candidate;

                boolean aInstanceOfStackingContext = a instanceof StackingContext;
                boolean bInstanceOfStackingContext = b instanceof StackingContext;

                if(aInstanceOfStackingContext && bInstanceOfStackingContext){
                    int ai = ((StackingContext)a).getZIndex();
                    int bi = ((StackingContext)b).getZIndex();
                    if(ai<bi){  return -1;
                    }else if(ai>bi){  return 1;
                    }else{  return 0;}
                }else if(aInstanceOfStackingContext && !bInstanceOfStackingContext){
                    return ((StackingContext)a).getZIndex()<0? -1: 1;
                }else if(!aInstanceOfStackingContext && bInstanceOfStackingContext){
                    return ((StackingContext)b).getZIndex()<0? 1: -1;
                }else /* if(!aInstanceOfStackingContext && !bInstanceOfStackingContext) */{
                    return ((Candidate)a).compareTo((Candidate)b);
                }
            }           
        };

        Queue<Object> queue = new LinkedList<Object>();
        queue.add(rootStackingContext);
        Object o;
        int i = 0;
        while((o = queue.poll()) != null){
            if(o instanceof StackingContext){
                Collections.sort(((StackingContext)o).getChildrens(), comparator);
                //reverse iterator
                ListIterator<Object> it = ((StackingContext)o).getChildrens().listIterator(((StackingContext)o).getChildrens().size());
                while(it.hasPrevious()){
                    queue.offer(it.previous());
                }
            }else /* if(o instanceof Candidate) */{
                candidates[i++] = (Candidate)o;
            }
        }

//      if(DOMUtil.DEBUG == true){
//          printTree(rootStackingContext, 0);      
//          printArray(candidates);
//      }
    }

    private static void initStackingContextsList(Candidate[] candidates, HashMap<Element, OverlappingDropTargetsHandler.StackingContext> cache){
        for(Candidate candidate : candidates) {
            Element stackingContextElement = findNearestStackingContextParentElement(candidate.getDropTarget().getElement());
            if(stackingContextElement != null){
                StackingContext stackingContext = cache.get(stackingContextElement);
                if(stackingContext == null){
                    stackingContext = new StackingContext(stackingContextElement);
                    cache.put(stackingContextElement, stackingContext);
                }
                stackingContext.addChildren(candidate);
            }
        }
    }

    /**
     * 
     * @param cache
     * @return the root StackingContext
     */
    private static StackingContext resolveStackingContextsHierarcy(HashMap<Element, OverlappingDropTargetsHandler.StackingContext> cache) {
        Queue<StackingContext> queue = new LinkedList<OverlappingDropTargetsHandler.StackingContext>(cache.values());

        StackingContext stackingContext;
        StackingContext rootStackingContext = null;
        while((stackingContext = queue.poll()) != null){
            Element parentElement = findNearestStackingContextParentElement(stackingContext.getElement());
            if(parentElement != null){
                StackingContext parentStackingContext = cache.get(parentElement);
                if(parentStackingContext == null){
                    parentStackingContext = new StackingContext(parentElement);
                    cache.put(parentElement, parentStackingContext);
                    queue.offer(parentStackingContext);
                }
                parentStackingContext.addChildren(stackingContext);
            }else{
                //this stackingContext is the root
                assert rootStackingContext == null || rootStackingContext == stackingContext;
                rootStackingContext = stackingContext;
            }
        }

        return rootStackingContext;
    }

    /**
     * @param element
     * @return the first parent that create a StackingContext or null if element is the root
     */
    private static Element findNearestStackingContextParentElement(Element element) {
        assert element != null;
        Element parentElement = element;
        while((parentElement = parentElement.getParentElement()) != null){
//          if(DOMUtil.DEBUG == true){
//              parentElement.getStyle().setProperty("border", "2px solid " + "orange");
//          }
            if(isStackingContext(parentElement)){
                return parentElement;
            }
//          if(DOMUtil.DEBUG == true){
//              parentElement.getStyle().setProperty("border", "2px solid " + "white");
//          }
        }
        return null;
    }

    private static native String getComputedProperty(Element e, String property)  /*-{
        return window.getComputedStyle(e).getPropertyValue(property);
     }-*/;  

    private static boolean isStackingContext(Element element) {
        String position = getComputedProperty(element, "position");
        String zindex = getComputedProperty(element, "z-index");

         if((!position.equals("static")) && (!zindex.equals("") && !zindex.equals("0"))){
            return true;
        }else if(RootPanel.get().getElement() == element){
            return true;
        }else{
            return false;
        }
        //TODO: gestire gli altri casi in cui viene creata un stacking context:

//      The root element always holds a root stacking context.
//
//      Setting z-index to anything other than 1 on an element that is positioned (i.e. an element with position that isn't static).
//
//      Note that this behavior is slated to be changed for elements with position: fixed such that they will always establish stacking contexts regardless of their z-index value. Some browsers have begun to adopt this behavior, however the change has not been reflected in either CSS2.1 or the new CSS Positioned Layout Module yet, so it may not be wise to rely on this behavior for now.
//
//      This change in behavior is explored in another answer of mine, which in turn links to this article and this set of CSSWG telecon minutes.
//
//      Another exception to this is with a flex item. Setting z-index on a flex item will always cause it to establish a stacking context even if it isn't positioned.
//
//      Setting opacity to anything less than 1.
//
//      Transforming the element:
//
//      Setting transform to anything other than none.
//
//      Setting transform-style to preserve-3d.
//
//      Setting perspective to anything other than none.
//
//      Creating a CSS region: setting flow-from to anything other than none on an element whose content is anything other than normal.
//
//      In paged media, each page-margin box establishes its own stacking context.
    }

    private static void printTree(StackingContext stackingContext, int level){  

        String s = "";
        for(int i = 0; i < level; i++) {
            s += "_";
        }

        for(Object o : stackingContext.getChildrens()){
            if(o instanceof StackingContext){
                Logger.getLogger("test").log(Level.WARNING, s + "(s) "+((StackingContext)o).getElement().getClassName()+" z-index="+ ((StackingContext)o).getZIndex());
                printTree((StackingContext)o, level+1);
            }else /* if(o instanceof Candidate) */{
                Logger.getLogger("test").log(Level.WARNING, s + "(c) "+((Candidate)o).getDropTarget().getElement().getClassName());
            }
        }
    }

    private static void printArray(Candidate[] candidates) {
        String s = "[";
        for(int i = 0; i < candidates.length; i++) {
            s+=candidates[i].getDropTarget().getElement().getNodeName();
            if(i < candidates.length-1){
                s += ", ";
            }
        }
        Logger.getLogger("test").log(Level.WARNING, s +"]");
    }
}