2021 年更新
引导程序 5
自定义文件输入不再存在,因此要更改 Choose file...,您需要使用 JS 或 some CSS like this。
引导 4.4
显示选定的文件名也可以使用纯 JavaScript 完成。这是一个假设标准自定义文件输入的示例,其标签是输入的下一个兄弟元素...
document.querySelector('.custom-file-input').addEventListener('change',function(e){
var fileName = document.getElementById("myInput").files[0].name;
var nextSibling = e.target.nextElementSibling
nextSibling.innerText = fileName
})
https://codeply.com/p/LtpNZllird
引导 4.1+
现在在 Bootstrap 4.1 中,“选择文件...”占位符文本设置在 custom-file-label:
<div class="custom-file" id="customFile" lang="es">
<input type="file" class="custom-file-input" id="exampleInputFile" aria-describedby="fileHelp">
<label class="custom-file-label" for="exampleInputFile">
Select file...
</label>
</div>
更改“浏览”按钮文本需要一些额外的 CSS 或 SASS。还要注意language translation works 是如何使用lang="" 属性的。
.custom-file-input ~ .custom-file-label::after {
content: "Button Text";
}
https://codeply.com/go/gnVCj66Efp (CSS)
https://codeply.com/go/2Mo9OrokBQ (SASS)
另一个 Bootstrap 4.1 选项
您也可以使用这个custom file input plugin
https://www.codeply.com/go/uGJOpHUd8L/file-input
Bootstrap 4 Alpha 6(原始答案)
我认为这里有两个不同的问题..
<label class="custom-file" id="customFile">
<input type="file" class="custom-file-input">
<span class="custom-file-control form-control-file"></span>
</label>
1 - 如何更改初始占位符和按钮文本
在 Bootstrap 4 中,initial 占位符值设置在 custom-file-control 上,并使用基于 HTML 语言的 CSS 伪 ::after 元素。初始文件按钮(它实际上不是一个按钮,但看起来像一个按钮)是使用 CSS 伪 ::before 元素设置的。这些值可以被 CSS 覆盖..
#customFile .custom-file-control:lang(en)::after {
content: "Select file...";
}
#customFile .custom-file-control:lang(en)::before {
content: "Click me";
}
2 - 如何获取选定的文件名值,并更新输入以显示该值。
选择文件后,可以使用 JavaScript/jQuery 获取值。
$('.custom-file-input').on('change',function(){
var fileName = $(this).val();
})
但是,由于输入的占位符文本是一个伪元素,there's no easy way to manipulate this with Js/jQuery。但是,您可以使用另一个 CSS 类,在选择文件后隐藏伪内容...
.custom-file-control.selected:lang(en)::after {
content: "" !important;
}
选择文件后,使用 jQuery 切换 .custom-file-control 上的 .selected 类。这将隐藏初始占位符值。然后把文件名的值放到.form-control-filespan...
$('.custom-file-input').on('change',function(){
var fileName = $(this).val();
$(this).next('.form-control-file').addClass("selected").html(fileName);
})
然后您可以根据需要处理文件上传或重新选择。
Demo on Codeply (alpha 6)