html5之拖放效果 (drag and drop)

来源:互联网 发布:易学大师宝宝取名软件 编辑:程序博客网 时间:2024/05/01 13:12

html部分

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="app.js"></script>
<style type="text/css">
    .box{
        width: 300px;
        height: 300px;
        float: left;
    }
    #box1{
        background-color: blue;
        
    }
    #box2{
        background-color: red;
        
    }

</style>

</head>

<body>

    <div class='box' id="box1"></div>
    <div class='box' id="box2"></div>
    <img id="img1" src="psb.jpg" width="100px;" height="100px;">
</body>
</html>



js部分

var box1,box2,img1;

window.onload = function(){
    
    box1 = document.getElementById("box1");
    box2 = document.getElementById("box2");
    img1 = document.getElementById("img1");
    
    //阻止默认的事件
    box1.ondragover = function(e){
        e.preventDefault();
    }
    box2.ondragover = function(e){
        e.preventDefault();
    }
    
    img1.ondragstart = function(e){
        e.dataTransfer.setData("imgid","img1");
        
    }
    box1.ondrop=droImghandler;
    box2.ondrop=droImghandler;
}

function droImghandler(e){
    var img = document.getElementById(e.dataTransfer.getData("imgid"));
    e.target.appendChild(img);
    
}

0 0
原创粉丝点击