🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 图片拖拉 ``` <style> .dropzone{ width: 100px; height: 100px; background-color: red; border: 1px solid #d0e9c6; } #view{ width: 100px; height: 100px; border:1px solid #0acb17; } </style> <body> <div class="dropzone"></div> 图片预览: <div id="view"></div> <script> document.addEventListener('dragover', function (event) { // 防止拖拉效果被重置,允许被拖拉的节点放入目标节点 event.preventDefault(); }, false); document.addEventListener('drop', function( event ) { // 防止事件默认行为(比如某些元素节点上可以打开链接), event.preventDefault(); if (event.target.className == "dropzone") { event.target.style.background = ''; var files = event.dataTransfer.files; for (var i = 0; i < files.length; i++) { var type = files[i].type; if (type.substring(0, 6) !== 'image/') continue; var img = document.createElement('img'); img.src = URL.createObjectURL(files[i]); img.onload = function () { this.width = 100; document.querySelector('#view').appendChild(this) URL.revokeObjectURL(this.src); } } } }); </script> </body> ``` ## 文件拖拉(待优化) ``` <div id="output" style="min-height: 200px;border: 1px solid black;"></div> var div = document.getElementById('output'); div.addEventListener("dragenter", function( event ) { div.textContent = ''; event.stopPropagation(); event.preventDefault(); }, false); div.addEventListener("dragover", function( event ) { event.stopPropagation(); event.preventDefault(); }, false); div.addEventListener("drop", function( event ) { event.stopPropagation(); event.preventDefault(); var files = event.dataTransfer.files; for (var i = 0; i < files.length; i++) { div.textContent += files[i].name + ' ' + files[i].size + '字节\n'; } }, false); ```