自定義input[type="file"]的兼容樣式

input[type="file"]的樣式在各個瀏覽器中的表現不盡相同:

1. chrome:

2. firefox:

3. opera:

4. ie:

5. edge:

另外,當我們規定 input[type="file"] 的高度,並把它的行高設置成與其高度相等後,chrome中難看的樣式出現了:


“未選擇任何文件”這一行並沒有豎直居中。

這些瀏覽器中的表現不一致,我們必須做兼容處理。

思路:

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 中:

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章