【问题标题】:Drag and drop and clone div element拖放和克隆 div 元素
【发布时间】:2012-05-19 08:40:06
【问题描述】:

您好,我在这里有一些 javascript,我想在其中实现拖放功能。因此,如果我单击一个 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;
    }
}

如果我不克隆目标,则拖动工作。如果我克隆它,拖动不起作用。知道为什么会这样吗?

【问题讨论】:

  • “如果我克隆了它,拖动不起作用”“不起作用”通常不足以描述。 :-) 什么 不起作用?你期望会发生什么?相反会发生什么?你看到了什么?

标签: javascript


【解决方案1】:

您永远不会将克隆添加到 DOM。在cloneNode之后,需要添加到容器中,例如:

target1 = target.cloneNode(true);
target.parentNode.appendChild(target1);

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 2013-06-15
    • 2014-11-14
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多