css - 如何自定义 Bootstrap 5 文件输入文本和按钮位置?

标签 css twitter-bootstrap bootstrap-4 bootstrap-5

Bootstrap 5 的输入类型文件过于简单。 https://getbootstrap.com/docs/5.1/forms/form-control/#file-input

file input bootstrap 5

我有 3 个问题:

  1. 是否可以将“选择文件”按钮移到右侧?
  2. 是否可以更改“未选择文件”消息?
  3. 是否可以更改“选择文件”消息?

可以使用 Bootstrap 4: https://getbootstrap.com/docs/4.6/components/input-group/#custom-file-input

谢谢!

最佳答案

我没有找到使用原始 Bootstrap 条目的解决方案。但是,我使用了一些技巧,就像我更改了文件输入表单的文本一样。我将使用您提供的示例来展示我是如何做到的。

这是来自 form-control of Bootstrap Docs 的输入表单. 代码是这样的:

    <div class="mb-3">
      <label for="formFile" class="form-label">Default file input example</label>
      <input class="form-control" type="file" id="formFile">
    </div>

思路是将file input tag替换为text input tag,使用Javascript绑定(bind)文件输入表单action。

    
<!-- use online bootstrap resource -->   
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<div class="mb-3">
  <label for="file_input_id" class="form-label">Default file input example</label>
                  
  <!-- use opacity and height style to hide file input form -->
  <input class="form-control" type="file" id="file_input_id" style="opacity:0;height:0;">
                  

  <!-- use another text input group to replace file input form -->
  <div class="input-group mb-3">
    <span class="input-group-text" id="text_input_span_id">Any text here</span>

    <!-- use 'caret-color: transparent' to hide input cursor, set autocomplete to off to remove possible input hint -->
    <input type="text" id='text_input_id' class="form-control" placeholder="Another text here" style="caret-color: transparent" autocomplete="off">
  </div>
</div>

<!-- use online jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  // bind file-input-form click action to text-input-span
  $('#text_input_span_id').click(function () {
    $("#file_input_id").trigger('click');
  })
  // bind file-input-form click action to text-input-form
  $('#text_input_id').click(function () {
    $("#file_input_id").trigger('click');
  })
  // display file name in text-input-form    
  $("#file_input_id").change(function () {            
    $('#text_input_id').val(this.value.replace(/C:\\fakepath\\/i, ''))
  })
</script>

单击输入表单并选择一个文件,成功了! choose file

如果想把按钮改到右边,只要改变span和input标签的顺序就可以了。

关于css - 如何自定义 Bootstrap 5 文件输入文本和按钮位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70453976/

相关文章:

twitter-bootstrap - 如何使 Bootstrap 事件在 vue 中工作

twitter-bootstrap - Bootstrap 4 : Dropdown menu is going off to the right of the screen

html - 使用内联样式在背景图像中加载错误

html - 一个分区的不同宽度...第二个分区应根据第一个分区进行调整

javascript - 如何使用成品排序功能

html - 将表单与 Bootstrap 4 中的中心对齐

JQuery 'animate' 函数无法平滑地设置 Bootstrap 进度条宽度的动画

html - 在文本字段中间对齐字体

javascript - Bootstrap 模态页眉和页脚未附加到正文

html - 如何让页脚停留在页面底部 bootstrap 4