【问题标题】:My input file is opening when I click outside of "choose file", how can I make it only open if the actual "button" is clicked?当我在“选择文件”之外单击时,我的输入文件正在打开,如何才能使其仅在单击实际的“按钮”时才打开?
【发布时间】:2019-06-24 00:57:15
【问题描述】:

我正在使用以下代码来设置文件上传。但是在我的页面上,输入元素的宽度大于显示的实际按钮。我可以单击这个不可见框中的任意位置,仍然可以打开文件浏览器。我希望能够单击按钮并将其打开,而不是空白。我怎样才能做到这一点?

<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />

【问题讨论】:

  • 请分享更多的html代码,这不足以重现问题
  • 因为这就是输入的工作方式,所以元素不仅仅是按钮。 jsfiddle.net/6to8cLsn
  • 这是组件的默认行为,我不认为您可以按照您指定的方式配置它。 Insted 你可能需要做这样的事情stackoverflow.com/questions/10798761/…

标签: javascript html css


【解决方案1】:

您可以隐藏文件按钮,并创建一个假的来模仿它。像这样:

var fakeButton = document.getElementById('fake-file-btn');
var fileButton = document.getElementById('selectFiles');
fakeButton.addEventListener('click', function(e) {

  // creates a event that triggers click on fileButton 
  var clickEvent = new MouseEvent('click', {bubbles: true});
  fileButton.dispatchEvent(clickEvent);
  
});
#selectFiles {
  display: none;
}
<button id="fake-file-btn">Choose File</button>
<input type="file" action="/upload" id="selectFiles" name="myFile" enctype="multipart/form-data" />

【讨论】:

    【解决方案2】:

    你是这个意思吗?

    <label>
        <input type="file" />
        <span class="file-button">Upload File</span>
    </label>
    
    label {
        display: inline-block;
    }
    
    label input[type="file"] {
        display: none;
    }
    
    .file-button {
        padding: 13px 20px;
        color: #fff;
        display: block;
        cursor: pointer;
        font-weight: 500;
        font-size: 0.8em;
        background: #f00;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2011-04-26
      • 2021-11-22
      • 2012-02-26
      • 1970-01-01
      • 2022-10-30
      • 2021-11-24
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多