我有这个脚本,将一个div拖到另一个div中:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style>
        .content {
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
        #dragme {
            height:50px;
            width:50px;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <div id="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
        <script>
            function allowDrop(ev) {
                ev.preventDefault();
            }

            function drag(ev) {
                ev.dataTransfer.setData("dragged-id", ev.target.id);
            }

            function drop(ev) {
                ev.preventDefault();
                var data = ev.dataTransfer.getData("dragged-id");
                ev.target.appendChild(document.getElementById(data));
            }
        </script>
</body>
</html>


一切正常,但是当我将“ dragme” div从id更改为class时,它将停止工作。这对我来说绝对没有意义。请帮忙 ?

最佳答案

http://jsfiddle.net/t98ZD/3/

<body>
<div class="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div class="dragme" draggable="true" ondragstart="drag(event)">Drag me!</div>
    <script>
        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            ev.dataTransfer.setData("dragged-id", ev.target.className);
        }

        function drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("dragged-id");
            ev.target.appendChild(document.getElementsByClassName(data)[0]);
        }
    </script>
</body>


CSS:

.dragme {
 height:50px;
width:50px;
background-color: blue;
}

09-10 11:21
查看更多