首页 > 代码库 > 拖拽事件_2

拖拽事件_2

  • 技术分享
     1    *{margin: 0;padding: 0;}
     2    li{list-style: none;
     3        height: 30px;
     4        width: 100px;
     5        margin: 10px;
     6        background-color: yellow;}
     7    #div1{
     8         margin: 100px;
     9         height: 100px;
    10         width: 100px;
    11         background-color: red;
    12    }
    View Code
    技术分享
     1 window.onload=function(){
     2     var oUl=document.querySelector("ul");
     3     var aLi=document.getElementsByTagName(‘li‘);
     4     var oDiv=document.getElementById("div1");
     5     var i=0;
     6     for(var i=0;i<aLi.length;i++){
     7          aLi[i].index=i;
     8         aLi[i].ondragstart=function(ev){
     9             var ev=ev||event;
    10             //dataTransfer.setData():设置数据 key和value(必须是字符串)
    11             ev.dataTransfer.setData("index",this.index);;
    12             this.style.backgroundColor="red";
    13         }
    14         aLi[i].ondrag=function(){
    15             document.title=i++;
    16         }
    17         aLi[i].ondragend=function(){
    18             this.style.backgroundColor="teal";
    19         }
    20     }
    21 
    22     oDiv.ondragenter=function(){
    23         this.style.background="yellow";
    24     }
    25     oDiv.ondragover=function(ev){
    26         var ev=ev||event;
    27         ev.preventDefault();
    28         document.title=i++;
    29     }
    30     oDiv.ondrop=function(ev){
    31         var ev=ev||event;
    32         //ev.dataTransfer.getData()获取数据,根据key值,获取对应的value
    33         //alert(ev.dataTransfer.getData("index"));
    34         var index=ev.dataTransfer.getData("index");
    35         oUl.removeChild(aLi[index]);
    36         for(var i=0;i<aLi.length;i++){
    37             aLi[i].index=i;
    38         }
    39     }
    40     oDiv.ondragend=function(){
    41         this.style.backgroundColor="";
    42     }
    43 
    44 }
    View Code

     

    a
  • b
  • c
 技术分享

 

 

拖拽事件_2