自定义input file 样式

该文章展示了如何使用HTML、CSS和JavaScript来美化原生的文件上传组件。通过隐藏默认的文件选择按钮,创建自定义样式的上传容器和按钮,以及添加动态显示选定文件名的功能,实现了更加用户友好的文件上传体验。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html>
<head>
  <title>美化原生HTML上传文件</title>
  
  <style>
    /* 隐藏默认的文件选择按钮 */
    .input-file {
      display: none;
    }

    /* 定义自定义样式的文件上传容器 */
    .custom-file-upload {
      position: relative;
      display: inline-block;
      overflow: hidden;
      padding: 8px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      cursor: pointer;
    }

    /* 自定义样式的按钮 */
    .custom-file-upload label {
      display: inline-block;
      background-color: #3498db;
      color: white;
      padding: 6px 12px;
      border-radius: 4px;
      cursor: pointer;
    }

    /* 可选:添加鼠标悬停和按下效果 */
    .custom-file-upload label:hover,
    .custom-file-upload label:active {
      background-color: #2980b9;
    }

    /* 显示选中的文件名 */
    #file-name {
      display: inline-block;
      margin-left: 10px;
    }
  </style>

</head>
<body>
  <div class="custom-file-upload">
    <input type="file" id="file-input" class="input-file">
    <label for="file-input"><i class="fa fa-cloud-upload"></i>拿来吧你</label>
    <span id="file-name">没有选择文件</span>
  </div>

  <script>
    var fileInput = document.getElementById('file-input');
    var fileNameLabel = document.getElementById('file-name');

    fileInput.addEventListener('change', function() {
      if (this.files.length > 0) {
        fileNameLabel.textContent = this.files[0].name;
      } else {
        fileNameLabel.textContent = '没有选择文件';
      }
    });
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一种可能的实现方式如下所示: 1. 创建一个包含样式的CSS类或者ID。 ```css .custom-file-input { position: absolute; /* 使文件选择框覆盖在自定义的按钮之上 */ opacity: 0; /* 隐藏默认的文件选择框 */ z-index: -1; /* 避免文件选择框挡住其他内容 */ } .custom-file-label { /* 自定义样式的文件选择文本 */ background-color: #007bff; color: #fff; border-color: #007bff; } .custom-file-label::after { /* 自定义样式的“选择文件”文本 */ content: '选择文件'; display: inline-block; background-color: #28a745; color: #fff; border-radius: 4px; padding: 6px 12px; cursor: pointer; } ``` 2. 在HTML文件中添加一个文件选择框和一个自定义按钮,使用相同的label标签关联它们。 ```html <label class="custom-file-label" for="customFile">选择文件</label> <input type="file" class="custom-file-input" id="customFile"> ``` 3. 使用JavaScript来监听文件选择框的change事件,当用户选择文件后更新自定义文本框的文本。 ```javascript // 获取文件选择框和自定义文本框 const fileInput = document.getElementById('customFile'); const fileLabel = fileInput.nextElementSibling; // 监听文件选择框的change事件 fileInput.addEventListener('change', function(event) { const fileName = event.target.files[0].name; // 更新自定义文本框的文本 fileLabel.innerText = fileName; }); ``` 这样就实现了一个简单的自定义样式的文件选择框。注意,上述实现方式可能不兼容所有浏览器和操作系统,需要进行相应的兼容性测试和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值