拖动div及其所有子div

时间:2010-04-09 17:51:42

标签: dom drag-and-drop javascript

我有以下代码:

<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 个答案:

答案 0 :(得分:2)

I did something similar使用Zorn的库并一起使用Prototype尝试制作某种类似visio的工具。我从来没有完成它,但在这个过程中学到了很多东西。它使用draggables,所以也许你会使用代码。只需查看页面源代码即可。

答案 1 :(得分:2)

jQuery-UI Draggable对我来说效果很好而且设置起来很简单。 http://jqueryui.com/demos/draggable/它适用于您的方案,我刚测试过它。

一旦你包含了jQuery和jQuery-UI,就可以执行以下操作将容器DIV转换为可拖动的DIV:

<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 :(得分:0)

问题是,我假设您的onmousedown处理程序中您使用的是事件对象的srcElementtarget属性。当你这样做时,你将会得到最内在的孩子(由于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>
相关问题