我们可以使用 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*/ }
以下示例说明了 CSS 文件选择器按钮选择器。
<!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> <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>
这会在 Firefox Web 浏览器中提供以下输出。
<!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> <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>
这会在 Google Chrome 中提供以下输出。