试试html5的拖拉事件和FileReader
<html> <head> <meta charset="utf-8" /> <title>file test</title> <script type="text/javascript"> (function(window) { var zImgUtil = window.zImgUtil || {}; var handler = function(event, imgHolderDomId, maxWidth) { if (!event) { return; } event.stopPropagation(); event.preventDefault(); if (event.type == "drop") { var data = event.dataTransfer; if (!data) { return; } if (!data.files || !data.files[0]) { return; } var file = data.files[0]; var fileReader = new FileReader(); fileReader.onloadend = function () { var data = this.result.substr(this.result.indexOf(',') + 1); var imgId = "img" + new Date().getTime(); document.getElementById(imgHolderDomId).innerHTML = "<img id='" + imgId + "' src='data:" + file.type + ";base64," + data + "' />"; if (maxWidth) { var imgDom = document.getElementById(imgId); if (maxWidth < imgDom.width) { var newHeight = maxWidth * imgDom.height / imgDom.width; imgDom.style.width = maxWidth; imgDom.style.height = newHeight; } } }; fileReader.readAsDataURL(file); } }; zImgUtil.dropAndShow = function(dropOnDomId, imgHolderDomId, maxWidth) { var srcDom = document.getElementById(dropOnDomId); var handlerWrapper = function(event) { handler(event, imgHolderDomId, maxWidth); }; srcDom.addEventListener("drop", handlerWrapper, false); srcDom.addEventListener("dragover", handlerWrapper, false); srcDom.addEventListener("dragenter", handlerWrapper, false); }; window.zImgUtil = zImgUtil; })(window); function init() { zImgUtil.dropAndShow("srcLabel", "imgDiv", 200); } </script> </head> <body onload="init()"> <div id="srcLabel" style="border: 1px solid green;min-height: 100px;"> <label id="srcLabel">拖进框里面试试看</label> <div id="imgDiv"></div> </div> </body> </html>
相关推荐
凉白开 2020-07-19
northwindx 2020-05-31
xdyangxiaoromg 2020-03-27
songfens 2019-12-14
VICHOUFA 2019-09-07
Chydar 2019-07-01
skyGAYD 2019-04-29
xuanbai 2016-09-05
htmlgood 2016-06-09
markshuai 2016-05-07
yaoliuwei 2015-12-08
DreamPig 2019-06-27
PioneerFan 2015-04-03
zjnig的信息仓库 2014-01-24
CoreyJia 2013-09-21
laxexue 2019-06-25
renpinghao 2019-06-21
yixiaof 2019-06-21
tanjiayq 2019-06-10