拖拽图片添加到页面

  1. <div id="drag" style="width: 50px;height: 50px; background-color:#e32;"></div>
  2. <script>
  3. let drag = document.querySelector('#drag');
  4. drag.addEventListener('dragover', (e) => {
  5. e.preventDefault();
  6. })
  7. drag.addEventListener('drop', (e) => {
  8. e.preventDefault();
  9. // e.dataTransfer.files[0]获取到拖拽对象的数据
  10. // console.log(e.dataTransfer.files[0]);
  11. // 创建一个fileReader对象
  12. let reader = new FileReader();
  13. reader.readAsDataURL(e.dataTransfer.files[0]);
  14. reader.onload = (e) => {
  15. // 获得上传文件的base64数据
  16. console.log(e.target.result);
  17. let img = new Image();
  18. img.src = e.target.result;
  19. document.body.appendChild(img);
  20. }
  21. })
  22. </script>

通过拖拽添加节点元素

  1. <p>Drop your favorite fruits below:</p>
  2. <ol ondragstart="dragStartHandler(event)" ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)" ondrop="dropHandler(event)">
  3. <li draggable="true" data-value="fruit-apple">Apples</li>
  4. <li draggable="true" data-value="fruit-orange">Oranges</li>
  5. <li draggable="true" data-value="fruit-pear">Pears</li>
  6. </ol>
  7. <script>
  8. var internalDNDType = 'text/x-example'; // set this to something specific to your site
  9. function dragStartHandler(event) {
  10. console.log("dragStartHandler");
  11. if (event.target instanceof HTMLLIElement) {
  12. // use the element's data-value="" attribute as the value to be moving:
  13. event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
  14. event.dataTransfer.effectAllowed = 'move'; // only allow moves
  15. } else {
  16. event.preventDefault(); // don't allow selection to be dragged
  17. }
  18. }
  19. function dragEnterHandler(event) {
  20. console.log("dragEnterHandler");
  21. var items = event.dataTransfer.items;
  22. for (var i = 0; i < items.length; ++i) {
  23. var item = items[i];
  24. if (item.kind == 'string' && item.type == internalDNDType) {
  25. event.preventDefault();
  26. return;
  27. }
  28. }
  29. }
  30. function dragOverHandler(event) {
  31. console.log("dragOverHandler");
  32. event.dataTransfer.dropEffect = 'move';
  33. event.preventDefault();
  34. }
  35. function dropHandler(event) {
  36. console.log("dropHandler");
  37. var li = document.createElement('li');
  38. var data = event.dataTransfer.getData(internalDNDType);;
  39. console.log("dropHandler==========", data);
  40. if (data == 'fruit-apple') {
  41. li.textContent = 'Apples';
  42. } else if (data == 'fruit-orange') {
  43. li.textContent = 'Oranges';
  44. } else if (data == 'fruit-pear') {
  45. li.textContent = 'Pears';
  46. } else {
  47. li.textContent = 'Unknown Fruit';
  48. }
  49. event.target.appendChild(li);
  50. }
  51. </script>