文件上傳時,默認的file標籤很難看,而且每個瀏覽器下都有很大差距。因此我們基本都把真正的file標籤給隱藏,然後創建一個標籤來替代它。但是由於IE出於安全方面的考慮上傳文件時必須點擊file的瀏覽按鈕選擇文件纔可以把文件上傳上去。此時我們可以將file input透明化, 遮罩在自定義的button input 上面。這樣用戶看到的是我們自定義button的外觀而實際上點擊的還是file標籤。
這樣一來我們自定義的按鈕存在又能真正點擊到file標籤,IE下就可以正常上傳文件了。
示例:
//html
<div class="modifyInfo_upload pr">
<span>上傳頭像</span>
<input type="file" name="portrait" id="upLoadPortrait" value="">
</div>
//css
.modifyInfo_upload{
height: 30px;
text-align: center;
margin-bottom: 29px;
}
.modifyInfo_upload span{
height: 30px;
line-height: 30px;
color: #1db69a;
cursor: pointer;
}
.modifyInfo_upload input{
width: 58px;
height: 20px;
overflow: hidden;
opacity: 0;
-ms-filter:"alpha(opacity=0)";
position: absolute;
top: 4px;
left: 0;
right: 0;
margin: 0 auto;
cursor: pointer;
}
//js
var portraitPath;
$("#upLoadPortrait").on('change',function(event){
if($(this).val() != ''){
var strExtension = $(this).val().substr($(this).val().lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif' && strExtension != 'png' && strExtension != 'bmp') {
alert("請選擇圖片文件!");
}else{
portraitPath = $(this).val();
console.log(portraitPath);
$('.modifyInfo_portrait img').attr('src',portraitPath);
}
}
});