【问题标题】:Get file name when css is applied to input[type=file]将 css 应用于 input[type=file] 时获取文件名
【发布时间】:2021-05-17 16:34:10
【问题描述】:

我正在尝试通过input 获取文件。 我通过 CSS 隐藏输入并给标签一个样式。这里有问题。

如果隐藏输入,则默认输入按钮不支持支持的获取文件名。 我想 Vanila JS 可以解决这个问题,但我不知道该怎么做。 我试图获取文件的value值,并将其放入指定为内部HTML的框中,但没有成功。

.submit{
   width:140px;
   height:40px;
   background-color:red;
   color:#fff;
   text-align:center;
   padding:10px;
   line-height:40px;
   cursor:pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
    <span class="submit">submit</span>
    <span id="test2">filename</span>
</label>

【问题讨论】:

标签: javascript html css


【解决方案1】:

按照Answer,你可以得到文件名,并使用innerHTML显示给用户。

document.getElementById('test').addEventListener("change", function() {
  var fullPath = document.getElementById('test').value;
  if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
      filename = filename.substring(1);
    }
    document.getElementById("test2").innerHTML = filename;;
  }
});
.submit {
  width: 140px;
  height: 40px;
  background-color: red;
  color: #fff;
  text-align: center;
  padding: 10px;
  line-height: 40px;
  cursor: pointer;
}
<input type="file" id="test" style="display:none;">
<label for="test">
    <span class="submit">submit</span>
    <span id="test2">filename</span>
</label>

【讨论】:

    【解决方案2】:

    你的 HTML

    <input type="file" id="test" style="display:none;">
    <label for="test">
        <span class="submit">submit</span>
        <span id="test2">filename</span>
    </label>
    

    你的 CSS

    .submit{
       width:140px;
       height:40px;
       background-color:red;
       color:#fff;
       text-align:center;
       padding:10px;
       line-height:40px;
       cursor:pointer;
     }
    

    还有 Javascript

    let file = document.querySelector('#test');
    let test2 = document.querySelector('#test2');
    
    file.addEventListener('change', function(e){
      test2.innerHTML = e.target.files[0].name;
    });
    

    在这里演示 https://jsfiddle.net/jozsefk/4gwzrj38/

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 2011-02-05
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多