第一步寫入input
.uploadWrap{
font-size: 14px;
line-height: 24px;
cursor: pointer;
height: 36px;
width: 118px;
margin-right: 6px;
margin-left: 28px;
position: relative;
}
.ph08{
opacity: 0; //如果自定義上傳按鈕一般都會(huì)這樣設(shè)置
height: 36px;
width: 118px;
position: absolute;
top: 0;
left: 0;
}
<div class="poster" id="poster"> </div>//圖片顯示dom
<button class="uploadWrap defaultBtn_low_short_noBg">
<input type="file" name="file0" id="file0" multiple="" class="ph08">
上傳海報(bào)
</button>
第二步j(luò)s獲取上傳圖片路徑
//處理圖片路徑
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;
}
$("#file0").change(function(){
if (this.files && this.files[0]){
var filePath = $('#file0').val().toLowerCase().split(".");
var fileType = filePath[filePath.length - 1]; //獲取圖片格式
if(fileType=='zip'||fileType=='rar'||fileType=='html'){
alert("請(qǐng)上傳圖片格式");
return false;
}
var objUrl = getObjectURL(this.files[0]);
if(objUrl){
console.log(objUrl);
$("#poster").css("background-image","url("+objUrl+")");
$("#file0").click(function(e){
$("#poster").css("background-image","url("+objUrl+")");
})
}
}
})
這樣獲取到圖片路徑直接放入到你想要顯示的dom就可以
效果.png