以前有介紹過關於把input[type='file']的輸入變爲相似於一個button的上傳,如今沿襲其思路一樣的製做一個自定義圖片的上傳類型,並可以實時顯示已經上傳的圖片。其原理簡單爲:採用絕對定位在頂層放一個<input type='file' />的標籤並把其透明度設置爲0,而後在一樣的位置採起絕對定位放置一個關閉按鈕(其z-index值得比input大),而後在一樣的位置採起絕對定位放置一個自定義的上傳圖片,最後放一個<img>標籤來獲取已上傳的圖片路徑並回顯到頁面上。html裏的結構爲:css
而後close.png和add.png均可以隨便本身找張圖片,我也是隨便找的因此比較醜。爲了看起來方便把css,js所有寫在頁面裏,其頁面代碼以下:html
<!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>
代碼實現的效果爲:初始狀態-jquery
點擊後彈出選擇文件框,並選擇圖片後顯示該圖片以及一個關閉按鈕:web
點擊關閉按鈕後又回覆到初始狀態:ide
整體來講input並不改變,只是在其下面多加了幾個標籤以及部分js代碼來實現對應的效果,可是這樣的圖片上傳比以前的會美化不少,能夠放在一個文件裏專門引用。this