js移入和移出
阿新 • • 發佈:2018-12-24
js移出和移入
<DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge" > <meta name="renderer" content="webkit" > <title>index</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <style> .container { width: 200px; height: 100px; margin-top: 20px; border: 1px solid #000; } </style> <script type="text/javascript"> $(function () { //開始 $('#drag1').on('dragstart', function (e) { e.originalEvent.dataTransfer.setData('text',e.target.id); }); //進入目標元素 $('.container').on('dragenter', function (e) { e.preventDefault(); }); //在目標元素上移動 $('.container').on('dragover', function (e) { e.preventDefault(); }); //移出目標元素 $('.container').on('dragleave', function () { }); //被拖拽元素被放置在目標元素上 $('.container').on('drop', function (ev) { //阻止預設行為 ev.preventDefault(); //阻止預設行為 ev.stopPropagation(); var data=ev.originalEvent.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); }); //拖拽結束 $('drag1').on('dragend', function (ev) { }); }) </script> <script type="text/javascript"> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <p>請把 W3School 的圖片拖放到矩形中:</p> <div class="container" > </div> <div class="container" style="margin-top: 50px"> <img id="drag1" src=" http://www.w3school.com.cn/i/eg_dragdrop_w3school.gif" draggable="true" ondragstart="drag(event)" /> </div> </body> </html>