input[type="file"]的樣式在各個瀏覽器中的表現不盡相同:chrome
1. chrome:瀏覽器
2. firefox:spa
3. opera:firefox
4. ie:code
5. edge:orm
另外,當咱們規定 input[type="file"] 的高度,並把它的行高設置成與其高度相等後,chrome中難看的樣式出現了:blog
「未選擇任何文件」這一行並無豎直居中。事件
彷佛在 firefox 中好看一些,嗯,我比較喜歡用 firefox。可是這些瀏覽器中的表現不一致,咱們必須作兼容處理。ip
思路:ci
1. 自定義與其中一個瀏覽器表現相似的樣式,將其放在下層;
2. 將瀏覽器自己的表現出來的樣式「隱藏掉」, opacity: 0; 置於上層,這樣咱們點擊的纔是 input[type="file"] 響應的事件;
3. 選擇文件或改變文件後,改變顯示 file 的值。
代碼:
<form action="" class="activityForm"> <div class="file"> <label for="file">文件:</label> <div class="userdefined-file"> <input type="text" name="userdefinedFile" id="userdefinedFile" value="未選擇任何文件"> <button type="button">上傳</button> </div> <input type="file" name="file" id="file"> </div> </form>
.file { position: relative; height: 40px; line-height: 40px; } .file label { display: inline-block; } .userdefined-file { position: absolute; top: 0; left: 60px; z-index: 2; width: 300px; height: 40px; line-height: 40px; font-size: 0; /*應對子元素爲 inline-block 引發的外邊距*/ } .userdefined-file input[type="text"] { display: inline-block; vertical-align: middle; padding-right: 14px; padding-left: 14px; width: 220px; box-sizing: border-box; border: 1px solid #ccc; height: 40px; line-height: 40px; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .userdefined-file button { display: inline-block; vertical-align: middle; width: 80px; text-align: center; height: 40px; line-height: 40px; font-size: 14px; background-color: #f54; border: none; color: #fff; cursor: pointer; } .file input[type="file"] { position: absolute; top: 0; left: 60px; z-index: 3; opacity: 0; width: 300px; height: 40px; line-height: 40px; cursor: pointer; }
document.getElementById("file").onchange = function() { document.getElementById("userdefinedFile").value = document.getElementById("file").value; }
這樣處理後,就在各個瀏覽器中表現一致了:
1. 未選擇任何文件時,在 chrome 中:
2. 在選擇文件後,在 firefox 中: