美文网首页
前端拖放垃圾桶效果

前端拖放垃圾桶效果

作者: 五四青年_4e7d | 来源:发表于2020-03-03 14:43 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
      ul li{
          width:100px;
          height:100px;
          border:1px solid red;
          list-style: none;
          text-align: center;
          float: left;
      }  
      .box{
          width:200px;
          height:200px;
          border:2px solid #000;
          float: left;
      }
    
      #txt{
           width:600px;
          height:100px;
          border:2px solid #000;
          float: left;  
      }
        
        </style>
    </head>
    <body>
        <ul>
            <li draggable="true">1</li>
            <li draggable="true">2</li>
            <li draggable="true">3</li>
            <li draggable="true">4</li>
            <li draggable="true">5</li>
        </ul>
        <p id="txt"></p>
    
    
        <div class="box"  id="out">
         垃圾箱
        </div>
    </body>
    </html>
    <script>
    
    window.onload = function(){
        var aLi = document.getElementsByTagName('li')
        var oDiv = document.getElementById("out")
        var txt = document.getElementById('txt')
      
        var targetLi = null   //存储拖拽的元素
    
        var img = document.createElement('img')
        img.src = 'https://img.yzcdn.cn/vant/apple-1.jpg'
    
        for(var i = 0; i < aLi.length;i++){
            aLi[i].ondragstart = function(ev){
                this.style.background = 'orange'
                targetLi = this
                ev.dataTransfer.setData('Text',this.innerHTML)
                ev.dataTransfer.setDragImage(img,20,20)
           
        }
        aLi[i].ondragend = function(){
            this.style.background = ''
        }
    
        oDiv.ondragenter = function(){
            this.style.background = 'red'
        }
    
        oDiv.ondragover = function(ev){
            ev.preventDefault()
        }
    
        oDiv.ondragleave = function(){
            this.style.borderColor = '#000'
        }
    
        oDiv.ondrop = function(ev){
            this.style.borderColor = '#000'
            var oText = ev.dataTransfer.getData('Text')
            txt.innerHTML = '删除的是' + oText
            targetLi.parentNode.removeChild(targetLi)
           
        }
    }
    
    
    }
    
    
    </script>
    

    相关文章

      网友评论

          本文标题:前端拖放垃圾桶效果

          本文链接:https://www.haomeiwen.com/subject/zbthlhtx.html