陷入HTML5拖放程序

时间:2013-06-29 09:46:52

标签: javascript html5 drag-and-drop

我正在学习HTML5,但遗憾的是他在一个例子中。此代码正在成功执行,但问题是拖放功能无法正常工作。我在这里粘贴代码。如果您发现任何错误请检查,请告诉我。

Thanx in Advance :)

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#boxA, #boxB {
float:left;padding:10px;margin:10px; -moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px;  }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>
<script type="text/javascript">
function dragStart(ev) {
ev.dataTransfer.effectAllowed='move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);
return true;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</div>

<div id="boxA" draggable="true" 
ondragstart="return dragStart(event)">
<p>Drag Me</p>
</div>
<div id="boxB">Dustbin</div>
</center>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

该框确实拖动但当然没有定义dragover或drop函数。这是我在学习的过程中创建的一个版本。它有点高级,因为它允许您指定放置每个可拖动元素的位置。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">

.box {  width: 350px;
    height: 70px;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #aaaaaa;}

.obj {  width: 220px;
    font-family: verdana, arial, sans-serif;
    font-size: 8pt;
    border: 2px solid #808080;
    border-radius: 4px; padding: 8px;}

#dragApp {
    background: #bbffbb;}

#dragAny { 
    position: absolute;
    left: 450px;
    top: 10px;
    background: #ffbbbb;}

#dragBox { 
    position: absolute;
    right: 10px;
    top: 10px;
    background: #bbbbff;}

</style>

<script>

function ge$(d) {
    var x = document.getElementById(d);
    if (!x) {
        var y = document.getElementsByName(d);
        if (y.length>0) x = y[0];
    }
    return x;
}


function addEventHandler(elem,eventType,handler) {
    if (elem.addEventListener)
        elem.addEventListener(eventType,handler,false);
    else if (elem.attachEvent)
        elem.attachEvent('on'+eventType,handler);
}

function removeEventHandler(elem,eventType,handler) {
    if (elem.removeEventListener)
        elem.removeEventListener(eventType,handler,false);
    if (elem.detachEvent)
        elem.detachEvent('on'+eventType,handler);
}

function stopBubble(e) {
    var evt = e ? e : window.event;
    if (evt.stopPropagation)    evt.stopPropagation();
    if (evt.cancelBubble!=null) evt.cancelBubble = true;
}

function stopDefault(e) {
    var evt = e ? e : window.event;
    if (evt.preventDefault) evt.preventDefault();
    evt.returnValue = false;
    return false;
}


dragObj = [];
dragBox = [];
dragApp = [];
dragItm = '';

setDrag = function(idObj, idBox, appChild) {
    if (dragObj.indexOf(idObj) == -1) {
        var obj = ge$(idObj);
        obj.draggable = true;
        addEventHandler(obj,'dragstart',drag_start,false);
        addEventHandler(obj,'dragend',drag_end,false);
        obj.style.cursor = 'move';
    }
    if (dragBox.indexOf(idBox) == -1) {
        var box = (idBox == 'body' ? document.body : ge$(idBox));
        addEventHandler(box,'dragover',drag_over,false); 
        addEventHandler(box,'drop',drag_drop,false); 
    }
    var i = dragObj.length;
    dragObj[i] = idObj;
    dragBox[i] = idBox;
    dragApp[i] = !!appChild;
}

function drag_start(e) {
    var evt = e ? e : window.event;
    this.style.opacity = 0.33;
    dragItm = this.id;
    var offsets = this.getBoundingClientRect();
    evt.dataTransfer.setData("Text", (offsets.left-evt.clientX) + ',' + (offsets.top-evt.clientY));
    evt.dataTransfer.effectAllowed = 'move';
}

function drag_end(e) {
    this.style.opacity = 1.0;}

function drag_over(e) {
    var evt = e ? e : window.event;
    var idObj = dragItm;
    var idBox = (evt.currentTarget == document.body ? 'body' : evt.currentTarget.id);
    var fnd = false;
    for (var i=0, len=dragObj.length; i<len; i++) {
        if (dragObj[i] == idObj && dragBox[i] == idBox) {
            fnd = true;
            break;
        }
    }
    if (fnd) {
        evt.dataTransfer.dropEffect = 'move';
        stopDefault(evt);
        stopBubble(evt);
    } else {
        evt.dataTransfer.dropEffect = 'none';
    }
}

function drag_drop(e) { 
    var evt = e ? e : window.event;
    var idObj = dragItm;
    var idBox = (evt.currentTarget == document.body ? 'body' : evt.currentTarget.id);
    var fnd = false;
    for (var i=0, len=dragObj.length; i<len; i++) {
        if (dragObj[i] == idObj && dragBox[i] == idBox) {
            fnd = true;
            var app = dragApp[i];
            break;
        }
    }
    if (fnd) {
        var obj = ge$(idObj);
        if (app) {
            evt.currentTarget.appendChild(obj);
        } else {
            var params = evt.dataTransfer.getData("Text").split(',');
            obj.style.left = (evt.clientX + parseInt(params[0],10)) + 'px';
            obj.style.top = (evt.clientY + parseInt(params[1],10)) + 'px';
        }
        stopDefault(evt);
        stopBubble(evt);
    }
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(value) {
        for (var i=0, len=this.length; i<len; i++) {
            if (this[i] === value) return i;
        }
        return -1;
    }
}

</script>
</head>

<body>

<div id="box1" class="box"></div>
<div id="box2" class="box"></div>

<div id="dragApp" class="obj">This one appends to either box.</div>
<div id="dragAny" class="obj">This one can be dragged anywhere.</div>
<div id="dragBox" class="obj">This one can only go in the top box.</div>

<p>I decided to look into HTML5 drag and drop. I found several examples online, but none seemed to 
provide any validation of where the items were being dragged except when they were actually dropped. 
So I created this page as an example of how to do it.</p>

<p>Note that the example built into this page won't work in IE9 as I've set DIV elements to drag, 
but IE9 only supports IMG and A-HREF elements.</p>

<p>I wrapped the whole thing in a setDrag function that takes in the ids of the object to be dragged 
and the location where it can be dropped. If the drop is to be completed by appending the object as a 
child then a third argument should be set to true.</p>

<p>There are seven events involved in dragging and dropping:</p>

<pre>
object      dragstart   when object first moved
        drag        while object is being moved
        dragend     when the object is dropped

target      dragenter   when object enters the target
        dragover    while object is over the target
        dragleave   when object leaves the target
        drop        when the object is dropped
</pre>

<p>The dragstart/dragend events are useful for changing the object appearance, and for initialling the 
cursor types and obect data in dataTransfer. The drag event isn't used here.</p>

<p>I don't use the dragenter/dragleave events. The drop event is the one that handles the moving of the 
object by changing its position/DOM location. The key is the dragover event as this determines where a 
drop can actually be made. The default is to not allow a drop so unless it performs a stopDefault() then 
no drop will be allowed.</p>
<br>

<p>There are some <b>gotchas:</b></p>

<p>In IE dragover can't use either THIS or dataTransfer to access the object info. So to get the id of 
the object in dragover you need to set a variable in dragstart.</p>

<p>In object events you can use event.target for the object (same as THIS) but in target events you have 
to use event.currentTarget (same as THIS) instead.</p>

<p>FF doesn't need to initialise the effectAllowed but IE does. I'm not use if setting the cursor to 'none' 
is required or not.</p>

<p>Because of event bubbling (I think) you still need to validate the combination of object/target in the 
drop event.</p>

<script>
setDrag('dragApp','box1',true);
setDrag('dragApp','box2',true);
setDrag('dragAny','body');
setDrag('dragBox','box1');
</script>

</body>
</html>