2012-05-10 15 views
0

こんにちは私はドラッグアンドドロップ機能を実装するいくつかのjavascriptをここに持っています。だからdiv要素をクリックしてドラッグすると、代わりに元のdivがそこにとどまるようにクローンをドラッグします。以下はドラッグアンドドロップでdiv要素を複製

私は、ドラッグ作品を対象のクローンを作成していない場合は私のスクリプト

var _startX = 0;    
var _startY = 0; 
var _offsetX = 0;   
var _offsetY = 0; 
var _dragElement;   
var _oldZIndex = 0;   
var _debug = $('.drag');  
var target1,target; 

function ExtractNumber(value) 
{ 
    var n = parseInt(value); 
    return n == null || isNaN(n) ? 0 : n; 
} 

// this is simply a shortcut for the eyes and fingers 
function $(id) 
{ 
    return document.getElementById(id); 
} 

InitDragDrop(); 

function InitDragDrop() 
{ 
    document.onmousedown = OnMouseDown; 
    document.onmouseup = OnMouseUp; 
} 

function OnMouseDown(e) 
{ 
    if (e == null) 
     e = window.event; 

    target = e.target != null ? e.target : e.srcElement; 

    if (target.className == 'drag') 
    { 
     _startX = e.clientX; 
     _startY = e.clientY; 

     target1 = target.cloneNode(true); 

     // grab the clicked element's position 
     _offsetX = ExtractNumber(target1.style.left); 
     _offsetY = ExtractNumber(target1.style.top); 

     // bring the clicked element to the front while it is being dragged 
     _oldZIndex = target1.style.zIndex; 
     target1.style.zIndex = 10000; 

     // we need to access the element in OnMouseMove 
     _dragElement = target1; 

     // tell our code to start moving the element with the mouse 
     document.onmousemove = OnMouseMove; 
    } 
} 

function OnMouseMove(e) 
{ 
    if (e == null) 
     var e = window.event; 

    // this is the actual "drag code" 
    _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; 
    _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; 
} 

function OnMouseUp(e) 
{ 
    if (_dragElement != null) 
    { 
     _dragElement.style.zIndex = _oldZIndex; 
     document.onmousemove = null; 
     _dragElement.ondragstart = null;  
     _dragElement = null; 
    } 
} 

です。私がそれを複製した場合、ドラッグは機能しません。なぜこのようなことが起こるのか?

+0

*「私はそれをクローン化した場合、ドラッグは動作しません」*通常は十分な説明ではありません「動作しません」。 :-) *何がうまくいかない?何が起こると思いますか?代わりに何が起こるのですか?あなたは何を見ますか? –

答えて

1

DOMにクローンを追加することはありません。 cloneNode後は、例えば、コンテナに追加する必要があります。:

target1 = target.cloneNode(true); 
target.parentNode.appendChild(target1); 
関連する問題