帶有 ::file-selector-button 選擇器的檔案上傳按鈕的 CSS 樣式


我們可以使用 CSS 偽元素 ::file-selector-button 設定檔案上傳按鈕的樣式。但是,此偽元素僅在 Firefox 和 Firefox Android 中得到完全支援。::-webkit-file-upload-button 用於支援 Safari、Chrome 和 Opera。

語法

CSS 檔案選擇器屬性的語法如下 −

Selector::file-selector-button {
   attribute: /*value*/
}
Selector::-webkit-file-upload-button {
   attribute: /*value*/
}

帶有 ::file-selector-button 的樣式檔案上傳按鈕

以下示例說明了 CSS 檔案選擇器按鈕選擇器。在 hover 時,我們已經這樣設定了樣式 −

input[type=file]::file-selector-button:hover {
   cursor: grab;
   background-color: blueviolet;
   color: white;
   font-size: 1.2em;
   box-shadow: inset 5px 10px 10px cornflowerblue;
}

注意 cursor 屬性 −

cursor: grab;

示例

讓我們看一個使用 ::file-selector-button 對檔案上傳按鈕設定樣式的示例 −

<!DOCTYPE html>
<html>
<head>
   <style>
      input[type=file]::file-selector-button:hover {
         cursor: grab;
         background-color: blueviolet;
         color: white;
         font-size: 1.2em;
         box-shadow: inset 5px 10px 10px cornflowerblue;
      }
   </style>
</head>
<body>
   <h1>Upload</h1>
   <form>
      <label for="fup">Click to</label>
      <input type="file" id="fup" />
      <input type="text" placeholder="Random Text here" />
      <button type="submit">Done</button>
   </form>
</body>
</html>

使用 ::-webkit-file-selector-button 設定檔案上傳按鈕的樣式

我們已經使用 ::-webkit 字首設定了檔案上傳按鈕的樣式。它是 Web 瀏覽器利用的渲染引擎,用於解釋和顯示 CSS 和 HTML −

input[type=file]::-webkit-file-upload-button:hover {
   cursor: pointer;
   background-color: crimson;
   font-size: 1.2em;
   border-radius: 25%;
   box-shadow: inset 5px 10px 10px cornsilk;
}

注意 cursor 屬性 −

cursor: pointer;

示例

我們看看一個使用 ::-webkit-file-selector-button 設定檔案上傳按鈕樣式的示例

<!DOCTYPE html>
<html>
<head>
   <style>
      input[type=file]::file-selector-button:hover {
         cursor: pointer;
         background-color: crimson;
         font-size: 1.2em;
         border-radius: 25%;
         box-shadow: inset 5px 10px 10px cornsilk;
      }
      input[type=file]::-webkit-file-upload-button:hover {
         cursor: pointer;
         background-color: crimson;
         font-size: 1.2em;
         border-radius: 25%;
         box-shadow: inset 5px 10px 10px cornsilk;
      }
   </style>
</head>
<body>
   <h1>Upload</h1>
   <form>
      <label for="fup">Click to</label>
      <input type="file" id="fup" />
      <input type="text" placeholder="using webkit prefix" />
      <button type="submit">Done</button>
   </form>
</body>
</html>

更新於: 2023 年 10 月 31 日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.