首页 > 代码库 > Datatransfer对象

Datatransfer对象

拖放触发的拖放事有一个datatransfer属性,该属性值是一个Datatransfer对象,利用这个方法可以实现一个简单的添加删除的拖放事件

<html>

<head>
    <meta charset="utf-8">
    <meta name="author" content="dongfeng">
    <title>通过拖放实现添加和删除</title>
    <style>
            div>div{
                display: inline-block;
                padding: 10px;
                background: #aaa;
                margin: 3px;
            }
        </style>
</head>

<body>
    <div style="width: 600px;border: 1px solid black;">
<h2>可将喜欢的项目拖入收藏夹</h2>
<div draggable="true" ondragstart="dsHandler(event)">javascript</div>
<div draggable="true" ondragstart="dsHandler(event)">css</div>
<div draggable="true" ondragstart="dsHandler(event)">angularjs</div>
<div draggable="true" ondragstart="dsHandler(event)">react</div>
</div>
<div id="dest" style="width: 400px;height: 400px;border: 1px solid black;float: left;">
<h2 ondragleave="return false">收藏夹</h2>
</div>
<img src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=854515879,1457472063&fm=23&gp=0.jpg" alt="垃圾桶" id="gb" draggable="false" style="float: left;">
<script>
var dest=document.getElementById(dest);
var dsHandler=function(ev){
    // 将被拖动元素的innerHtml属性值设为被拖动的数据
    ev.dataTransfer.setData(text/plain,"<item>"+ev.target.innerHTML);
}
dest.ondrop=function(ev){
    var text=ev.dataTransfer.getData(text/plain);
    // 
    if(text.indexOf(<item>)==0){
        // 
        var newEle=document.createElement(div);

        // 
        newEle.id=new Date().getUTCMilliseconds();
        // 
        newEle.innerHTML=text.substring(6);
        // 
        newEle.draggable=true;
        // 
        newEle.ondragstart=function(ev){
            ev.dataTransfer.setData(text/plain,<remove>+newEle.id);
        }
        dest.appendChild(newEle);
    }
}
// 
document.getElementById(gb).ondrop=function(ev){
    var id=ev.dataTransfer.getData(text/plain);
    if(id.indexOf(<remove>)==0){
        // 
        var target=document.getElementById(id.substring(8));
        //
        dest.removeChild(target); 
    }
}
document.ondragover=function(ev){
    return false
}
document.ondrop=function(ev){
    return false
}

</script>
</body>

</html>

 

Datatransfer对象