標籤:
在網上找了很久上傳檔案的樣式,並沒有適合自己的,現在推薦一個樣式給大家,可以看到自己是否選到檔案和檔案名稱。效果如所示:
html 代碼如下:
<div class="uploading"> <span>上傳檔案:</span> <input class=‘view‘ id="viewfile" type="text" onmouseout="document.getElementById(‘uploadfile‘).style.display = ‘none‘;" readonly /> <label class="filelab" for="uploadfile" onmouseover="document.getElementById(‘uploadfile‘).style.display = ‘block‘;">瀏覽</label> <input class="upload" id="uploadfile" name="uploadfile" type="file" /></div>
css 代碼如下:
.uploading { position: relative; height: 28px;}.uploading span { float: left; line-height: 28px;}.uploading .view { float: left; width: 120px; height: 26px; padding: 0 0 0 10px; line-height: 26px; border: 1px solid #d2d2d2;}.uploading .filelab { display: inline-block; float: left; width: 68px; height: 28px; line-height: 28px; text-align: center; color: #fff; background: #bd3a39;}.uploading .upload { position: absolute; left: 302px; width: 68px; height: 28px; opacity: 0; filter: alpha(opacity=0);}
最後 js代碼如下:
1 var uploadfile = document.getElementById(‘uploadfile‘);2 var viewfile = document.getElementById(‘viewfile‘);3 uploadfile.onchange = function() {4 var value = uploadfile.value.split(‘\\‘)[2]||‘‘; 5 viewfile.setAttribute(‘value‘, value);6 uploadfile.style.display = ‘none‘;7 }
對於第4行代碼,可能有點難理解,如果列印出 uploadfile.value 值,它是 ‘C:\fakepath\demo.rar‘, ‘C:\fakepath\‘ 是自動產生的假路徑,只要把假路徑刪除就行了,通過 split 方法把這個字串以 ‘\‘ 分隔產生一個數組 ["C:", "fakepath", "demo.rar"],取出數組中下標為2的就是想要的檔案名稱 ‘demo.rar‘,如果重新選擇檔案時取消上傳,也會觸發 change 事件,uploadfile.value 值為空白,同時也會把之前選的檔案刪除。
上傳檔案的樣式