代码之家  ›  专栏  ›  技术社区  ›  user113476

拖动一个div及其所有子div

  •  2
  • user113476  · 技术社区  · 16 年前

    我有以下代码:

    <body>
        <div id="container" style="position:absolute; left:0px; top:0px; z-index:1;">
            <div id="div1" style="background-color:Red; position:absolute; left:0px; top:0px; width:256px; height:256px; z-index:0;" >&nbsp;</div>
            <div id="div2" style="background-color:Black; position:absolute; left:256px; top:0px; width:256px; height:256px; z-index:0;" >&nbsp;</div>
            <div id="div3" style="background-color:Green; position:absolute; left:512px; top:0px; width:256px; height:256px; z-index:0;" >&nbsp;</div>
            <div id="div4" style="background-color:Yellow; position:absolute; left:768px; top:0px; width:256px; height:256px; z-index:0;" >&nbsp;</div>
            <div id="div5" style="background-color:Blue; position:absolute; left:1024px; top:0px; width:256px; height:256px; z-index:0;" >&nbsp;</div>
        </div>
    
        <script type="text/javascript">
            <!--
    
            SET_DHTML("container");
    
            //-->
        </script> 
    </body>
    

    我想拖动“container”div,以便同时拖动所有子div。我可以拖动单个div,但这不是我想要的。div可以拖动子div还是必须是图像?

    我使用的是WalterZorn拖放API,但我愿意使用任何API、脚本或任何东西。

    3 回复  |  直到 16 年前
        1
  •  2
  •   7wp    16 年前

    jqueryui Draggable对我来说工作得很好,设置起来非常简单。 http://jqueryui.com/demos/draggable/

    <script type="text/javascript">    
    
        //This makes sure that the code only runs once the whole
        //HTML document has been loaded into the Browser.
        $(document).ready(function(){
                $("#container").draggable();  //Intialize the Draggable ability
        });        
    </script>
    
        2
  •  2
  •   Diodeus - James MacFarlane    16 年前

    I did something similar 使用Zorn的库和Prototype一起尝试制作一些类似visio的工具。我从未完成,但在这个过程中学到了很多。它使用了draggables,所以也许您可以使用一些代码。只要查看页面源代码,就可以了。

        3
  •  0
  •   geppy Greg Lyon    15 年前

    我想问题是你的 onmousedown 正在使用事件对象的 srcElement target 属性。当你这么做的时候,你会得到最内在的孩子(由于 bubbling

    但是,如果你用 the this variable in your event handler ,您将获得在其上注册事件的DOM元素。下面是两个例子。

    <script type="text/javascript">    
    function onMouseDown(e) {
        var event = e || window.event;
        var element = event.target || event.srcElement; //refers to innermost element
    
        onDragStart(element, event);
    }
    </script>
    

    正确示例:

    <script type="text/javascript">  
    function onMouseDown(e) {
        var event = e || window.event;
        var element = this; // refers to the element that you set the callback on
    
        onDragStart(element, event);
    }
    </script>