瀏覽器默認渲染的文件上傳控件樣式固定、難看,且無法直接通過 CSS 修改「選擇文件」按鈕的文字或圖標。
<style>
.file-wrapper {
display: inline-block;
position: relative;
overflow: hidden;
cursor: pointer;
}
.file-wrapper input[type="file"] {
position: absolute;
left: 0; top: 0;
opacity: 0;
filter: alpha(opacity=0);
font-size: 100px; /* 放大點擊區域 */
width: 100%; height: 100%;
}
.custom-btn {
display: inline-block;
padding: 8px 16px;
background: #007bff;
color: #fff;
border-radius: 4px;
background-image: url('upload-icon.png');
background-repeat: no-repeat;
background-position: 8px center;
padding-left: 32px;
}
</style>
<div class="file-wrapper">
<span class="custom-btn">上傳圖片</span>
<input type="file" name="myfiles" accept="image/*" />
</div>
display:none,保證控件仍可接收點擊事件。filter: alpha(opacity=0)。<script>
document.querySelector('.file-wrapper input').addEventListener('change', function(e) {
const fileName = e.target.files[0]?.name || '未選擇文件';
this.previousElementSibling.textContent = fileName;
});
</script>
此方案無需任何 JS 庫,純 CSS/HTML 實現,兼容所有主流瀏覽器(含移動端)。