html-拖放-Drag&Drop
阿新 • • 發佈:2020-11-05
用處及優勢
- 提供專門的拖拽與投放的API
- 出發多個事件,可控制滑鼠的形狀與移動是的效果
- 可以跨頁面拖放
拖放API的基本操作語法
draggabel屬性
拖拽事件-ondragstart , drag , dragend
拖放事件-dragenter , dragover , drop
dataTransfer物件- setData / getData / setDragImage
實現拖拽垃圾桶效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ margin: 0; } ul{ overflow: hidden; padding: 0; margin: 0; } li{ width: 100px; height: 50px; line-height: 50px; text-align: center; border: 1px solid #000; /* margin: 20px; */ float: left; list-style: none; } #out{ width: 100px; height: 150px; line-height: 150px; margin: 50px; border: 1px solid #000; text-align: center; } </style> </head> <body style="position:relative"> <ul> <li draggable="true">白色垃圾</li> <li draggable="true">生活垃圾</li> <li draggable="true">廚餘垃圾</li> <li draggable="true">有害垃圾</li> <li draggable="true">可回收垃圾</li> </ul> <p id="txt"></p> <div id="out">垃圾箱</div> </body> <script type="text/javascript"> window.onload=function(){ let ali=document.getElementsByTagName('li') let oDiv=document.getElementById("out") let txt=document.getElementById("txt") let targetLi=null //用來儲存當前拖拽的dom元素 let img=document.createElement('img')//定義拖拽的圖片 img.src='img/1111.jpg' //給沒給拖拽元素賦方法 for(var i=0;i<ali.length;i++){ //開始 ali[i].ondragstart=function(ev){ this.style.background='yellow' targetLi=this ev.dataTransfer.setData('Text',this.innerHTML) //文字資料的攜帶 // ev.dataTransfer.setDragImage(img,20,20) } //結束 ali[i].ondragend=function(e){ this.style.background='' } } oDiv.ondragenter=function(){ this.style.borderColor='red' } oDiv.ondragover=function(e){ // console.log(e) e.preventDefault() } oDiv.ondragleave=function(e){ this.style.borderColor='#000' } oDiv.ondrop=function(ev){ this.style.borderColor='#000' let oText=ev.dataTransfer.getData('Text') txt.innerHTML='刪除的是:'+ oText targetLi.parentNode.removeChild(targetLi) } } </script> </html>