之前有介紹過關於把input[type='file']的輸入變為類似於一個button的上傳,現在沿襲其思路同樣的制作一個自定義圖片的上傳類型,並能夠實時顯示已經上傳的圖片。其原理簡單為:采用絕對定位在頂層放一個<input type='file' />的標簽並把其透明度設置為0,然后在同樣的位置采取絕對定位放置一個關閉按鈕(其z-index值得比input大),然后在同樣的位置采取絕對定位放置一個自定義的上傳圖片,最后放一個<img>標簽來獲取已上傳的圖片路徑並回顯到頁面上。html里的結構為:
然后close.png和add.png都可以隨便自己找張圖片,我也是隨便找的所以比較丑。為了看起來方便把css,js全部寫在頁面里,其頁面代碼如下:
<!doctype html>
<html>
<head>
<style> * { margin: 0; padding: 0;
}
/*上傳input*/ .myUpload { position: absolute; width: 130px; height: 100px; opacity: 0; z-index: 100;
}
/*關閉按鈕*/ .close { position: absolute; width: 20px; height: 20px; left: 110px; z-index: 200; cursor: pointer;
}
/*隱藏*/ .hide { display: none;
}
/*上傳的圖片*/ .add { position: absolute; width: 130px; height: 100px;
}
/*顯示上傳的圖片*/ .show { position: absolute; width: 130px; height: 100px;
}
</style>
<script src="../jquery-3.1.0.min.js"></script>
<title>pic類型的file自定義上傳</title>
</head>
<body>
<input type="file" class="myUpload" />
<img src="../images/close.jpg" class="close hide"/>
<img src="../images/add.png" class="add "/>
<img class="show hide"/>
</body>
</html>
<script> $(document).ready(function() { //點擊上傳時實時顯示圖片
$(".myUpload").change(function() { var src=getObjectURL(this.files[0]);//獲取上傳文件的路徑
$(".close").removeClass('hide'); $(".add").addClass('hide'); $(".show").removeClass('hide'); $(".show").attr('src',src);//把路徑賦值給img標簽
}); //點擊關閉按鈕時恢復初始狀態
$(".close").click(function() { $(".close").addClass('hide'); $(".add").removeClass('hide'); $(".show").addClass('hide'); }); }); //獲取上傳文件的url
function getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file); } else if (window.URL != undefined) { url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file); } return url; } </script>
代碼實現的效果為:初始狀態-
點擊后彈出選擇文件框,並選擇圖片后顯示該圖片以及一個關閉按鈕:
點擊關閉按鈕后又回復到初始狀態:
總體來說input並不改變,只是在其下面多加了幾個標簽以及部分js代碼來實現對應的效果,但是這樣的圖片上傳比之前的會美化很多,可以放在一個文件里專門引用。