最近做一套手機(jī)商城頁(yè)面,在退款申請(qǐng)頁(yè)面有上傳圖片顯示縮略圖的功能,以前沒(méi)有做過(guò)這個(gè),所以整理了一下同波。
首先 HTML :
<p>上傳圖片:</p>
<div id="imgPreview"></div>
<span class="upload-img"><input id="fileUpload" accept="image/*" type="file" multiple="multiple"></span>
</div>
CSS :
#imgPreview {
float: left;
border: none;
}
#imgPreview img {
margin-right: 10px;
width: 50px;
height: 50px;
}
upload-img {
display: block;
float: left;
width: 50px;
height: 50px;
overflow: hidden;
position: relative;
background: url("../images/self/upload.png") no-repeat 0;
background-size: contain;
}
//這兒是為了改變上傳按鈕樣式把input設(shè)為了透明色
.upload-img input {
height: 50px;
opacity: 0;
filter: alpha(opacity=0);
position: absolute;
top: 0;
right: 0;
}
在這里我把上傳按鈕input變成了透明色,然后用一個(gè)設(shè)置了+號(hào)背景圖的span蓋在上面實(shí)現(xiàn)了上傳按鈕的樣式改變叠国,如不用圖片也可以自行設(shè)置span樣式來(lái)達(dá)到想要的效果未檩。
JQuery :
<script type="text/javascript">
$(function () {
$("#fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#imgPreview");
dvPreview.html("");
var regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
</script>
給 input 綁定了一個(gè) change() 事件,當(dāng)事件被觸發(fā)后粟焊,首先會(huì)檢測(cè)該瀏覽器是否支持 HTML5 FileReader API ,如果支持就會(huì)執(zhí)行一個(gè) each 循環(huán)冤狡。
在每一個(gè)循環(huán)里,用正則表達(dá)式判斷文件后綴名是否為圖片格式项棠,如果是圖片格式悲雳,如果是圖片,就會(huì)用 readAsDataURL 方法來(lái)讀取其 BASE64編碼香追,然后以其為img元素的 src 屬性值合瓢,添加 img 元素到 #imgPreview 中,實(shí)現(xiàn)上傳顯示縮略圖翅阵。