How can I get a file upload button's text?

2020-04-10 03:03发布

问题:

I'm writing documentation for a web platform and I want to refer to a file upload button in my instructions. However, the exact text on the button depends on the browser. For example, Firefox calls it Browse... and Chrome calls it Choose File.

<input type="file">

Is it possible to access (not change) that text programmatically? I know I can detect the browser and set the text in the documentation accordingly, or even use a workaround to set the button text, but that's not what I'm asking.

回答1:

This text is set by how the browser renders that specific HTML element. There's no way to access or change that text. It will never be loaded into the DOM, so finding via jQuery is also not an option.

For your documentation, you may want to address what the IE version of the text will be, then list Chrome, Safari, Firefox, etc. It's the best way I can think of to explain to the user.

EDIT

Just thought I'd update and mention Shadow DOM because it's interesting and new to me. You can enable this in Chrome Dev Tools -> settings -> Show user agent shadow DOM. There you can actually view the rendered control and the text set to it. Although, it's not accessible programmatically through client side scripting. :(



回答2:

You could use a label for the input_id and hide the input.

Example:

label {
/*Just to simulate a button, you will put your button style*/
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  text-decoration: none;
  color: initial;
}

input {
/*hide the inout*/
  width: 0px;
  outline:none;
  opacity:0;
  visibility:none;
  height:0px;
  display:none;
}
<label for="b1">
    Name
    <input type="file" id="b1">
</label>

Working DEMO.



回答3:

Is it possible to access (not change) that text programmatically?

No. It is not possible to access the .value of the <input> element within <input type="file"> ShadowDOM which renders the text programmatically. The .shadowRoot property of <input type="file"> DOM element where the ShadowDOM is displayed is set to null.

Chrome, chromium exposes the .value of <input type="button" value="Choose File" pseudo="-webkit-file-upload-button"> at ShadowDOM of <input type="file"> element at .computedName property of input type="file" element

const UPLOAD_BUTTON_TEXT = document.querySelector("input[type=file]")
.computedName;
console.log(UPLOAD_BUTTON_TEXT);
<input type="file" />


At chrome, chromium you can view the element

<input type="button" value="Choose File" pseudo="-webkit-file-upload-button">

which renders the text at host <input type="file"> element by opening DevTools, selecting Settings, checking Show user agent shadow DOM, then inspecting the <input type="file"> element.

<input type="file">