1、準備工做javascript
1.默認素材:Img_add.pnghtml
2 使用window.FileReader :預覽java
2、以默認圖片覆蓋input:type="file"元素。瀏覽圖片,實現預覽 測試
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <title>測試圖片</title> </head> <body> <div class="FileDiv" style="position:relative;left:0;top:0;width:150px; height:150px;" > <input style="position:absolute;width:0px; height:0px;display:none;" type="file" accept="image/*" id="file" name="file" onchange="showPreview(this)" /> <img style="position:absolute;left:0;top:0;width:150px; height:150px;z-index:0;" width="150" height="150" id="portrait" src="Images/Img_add.png" onclick="document.getElementById('file').click()"> </div> </body> </html> <script type="text/javascript"> function showPreview(source) { var file = source.files[0]; if (!/image\/\w+/.test(file.type)) { alert("請確保文件爲圖像類型"); return false; } if (window.FileReader) { var fr = new FileReader(); fr.onloadend = function (e) { document.getElementById("portrait").src = e.target.result; document.getElementById("portrait").style.display = " inline-block"; }; fr.readAsDataURL(file); } } </script>