html5的拖拽

2019-10-17  本文已影响0人  Ben大师
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container{
            width:200px;
            height:200px;
            background: pink;
        }
        .target1{
            width:100px;
            height:100px;
            background: #398439;
        }
    </style>
</head>
<body>
<div id="container" class="container"></div>
<div id="target1" class="target1" draggable="true"></div>

<script>
    document.getElementById("target1").ondragstart=function (e) {
        e.dataTransfer.setData("text/plain",e.target.id);
    };
    document.getElementById("container").ondrop = function (e) {
        var data = e.dataTransfer.getData("text/plain");
        //console.log(data);
        e.target.appendChild(document.getElementById(data));
    }
    document.getElementById("container").ondragover = function (e) {
        e.preventDefault();
    }
</script>
</body>
</html>

最终效果:


GIF.gif
上一篇 下一篇

猜你喜欢

热点阅读