javascript拖放class / id问题

时间:2014-04-08 20:24:22

标签: javascript html css

我有这个脚本将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时,它会停止工作。这对我来说完全没有意义。请帮帮忙?

2 个答案:

答案 0 :(得分:3)

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;
}

答案 1 :(得分:1)

这就是它的工作原理:document.getElementById(data)