HTML:
<div class="pic">
<label for="pic1">
<input id="pic1" type="file" />
<img class="pic1 picc" src="images/pic_03.jpg" alt="" />
</label>
<label for="pic2">
<input id="pic2" type="file" />
<img class="pic2 picc" src="images/pic_03.jpg" alt="" />
</label>
<label for="pic3">
<input id="pic3" type="file" />
<img class="pic3 picc" src="images/pic_03.jpg" alt="" />
</label>
</div>
JS:
<script type="text/javascript">
$(function() {
$('.picc').each(function(i){
$(this).click(function(){
$(this).prev('input').on("change",function(){
//判断后缀
var filepath=$(this).val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
//console.log(extStart);
if(ext != ".JPG" && ext != ".PNG" && ext != ".JPEG"){
alert("上传的格式不对!");
return false;
}
//判断大小
var fileSzie = $(this)[0].files[0].size;
//console.log(fileSzie);
if(fileSzie > 10 * 1024 * 1024){
alert("图片太大咯!");
return false;
}
//图片预览
var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
//console.log(objUrl);
if(objUrl) {
$(this).next('.picc').attr("src", objUrl) ; //将图片路径存入src中,显示出图片
}
});
})
})
});
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
</script>