8

Boostrap 4 中的文件浏览器缺少文件名。它只是说选择文件...我为它制作了一个javascript解决方案。有没有更好的方法来解决它?

HTML

<label class="file">
    <input type="file" id="file1" >
    <span class="file-custom" data-content="Choose file..."></span>
</label>

jQuery

$("input[type=file]").change(function(){
    var fieldVal = $(this).val();
    if (fieldVal != undefined || fieldVal != "") {   
        $(this).next(".file-custom").attr('data-content', fieldVal);
    }
});

CSS

.file-custom:after {
    content: attr(data-content);
}

唯一的区别是您必须将数据内容添加到跨度。另一方面,它使更改语言更容易。

链接到 Bootstraps 文件浏览器:http: //v4-alpha.getbootstrap.com/components/forms/#file-browser

4

2 回答 2

6

看起来 Bootstrap 现在倾向于不为此添加 JS 解决方案,而是可能会在文档中包含类似于您的脚本的内容作为建议的实现,基于此处 mdo 的评论,其中还有一个更完整的解决方案: https: //github.com/twbs/bootstrap/issues/20813

我已经更新了 Bootstrap 4 Alpha 6 的简单代码。

jQuery

$("input[type=file]").change(function () {
  var fieldVal = $(this).val();
  if (fieldVal != undefined || fieldVal != "") {
    $(this).next(".custom-file-control").attr('data-content', fieldVal);
  }
});

CSS

.custom-file-control:after {
    content: attr(data-content) !important;
}

编辑:

上面将C:\\fakepath...在样式输入中显示类似的内容,我们也可以仅获取要显示的文件名本身,使用event.target.files[0].name

$("input[type=file]").change(function (event) {
  var fieldVal = event.target.files[0].name;
  if (fieldVal != undefined || fieldVal != "") {
    $(this).next(".custom-file-control").attr('data-content', fieldVal);
  }
});
于 2017-04-27T02:12:42.483 回答
1

跟进 Joey 的回答,对于 Bootstrap 4 公开发布,您现在将使用这个 JS 而没有 CSS:

$("input[type=file]").change(function () {
    var fieldVal = $(this).val();
    if (fieldVal != undefined || fieldVal != "") {
        $(this).next(".custom-file-label").text(fieldVal);
    }
});
于 2018-01-26T13:50:47.487 回答