Alter input type=“file” label content

2020-06-28 09:22发布

I was wondering if there is any way to hide or change the content of the default label:No file chosen for

<input type="file" id="myFileInput"/>

What I come up with so far is to decrease its length by half, so that it displays a tooltip.

$('input:file').css('width', parseFloat($($('input:file')).css('width'))/2 );

Any Ideas?

3条回答
Rolldiameter
2楼-- · 2020-06-28 09:31

You cannot change input file design as its native to each browser. But you still can simulate it, sorry hacky:

See DEMO

<button id="btn_myFileInput">Choose file...</button>
<label for="btn_myFileInput">No file choosen or whatever...</label>
<input type="file" id="myFileInput" multiple />​

JS:

$(function () {
    $('#btn_myFileInput').data('default', $('label[for=btn_myFileInput]').text()).click(function () {
        $('#myFileInput').click()
    });
    $('#myFileInput').on('change', function () {
        var files = this.files;
        if (!files.length) {
            $('label[for=btn_myFileInput]').text($('#btn_myFileInput').data('default'));
            return;
        }
        $('label[for=btn_myFileInput]').empty();
        for (var i = 0, l = files.length; i < l; i++) {
            $('label[for=btn_myFileInput]').append(files[i].name + '\n');
        }
    });
});
查看更多
叛逆
3楼-- · 2020-06-28 09:51

You can also proceed in this way, but it is an hack:

<input type="file" id="myFileInput" name="html" style="width: 90px;" onchange="this.style.width = '100%';"/>
查看更多
冷血范
4楼-- · 2020-06-28 09:53

Chrome was giving me this problem too. I tried to set all sorts of CSS selectors, but nothing seemed to work well. However, I did find a solution by using the FORM element.

  1. name your input[type=file] element.
  2. name your form element and put the input[type=file] in it.
  3. make a span and place it below the input in the form. This will be your label.
  4. use CSS to set the input's height to 0px and opacity to 0, this will make it invisible.
  5. make the span positioned absolutely and to the left 0px.
<style>
    #file {
        height:0px;
        opacity:0;
    }  
    #span {
        left:0px;
        position:absolute;
        cursor: pointer;
    }
</style>

<form name="form">
    <input type="file" id="file" name="file"/>
    <span id="span">My File label!!!!</span>
</form>

<script>
    var span = document.getElementById("span");

    span.onclick = function(event) {
        document.form.file.click(event);
    };

    var span = document.getElementById("span");
    span.onclick = function(event) {
        document.form.file.click(event);
    };
</script>

I tested this in Chrome and FF, not ie, but I hope this helps. jsfiddle http://jsfiddle.net/aressler38/L5r8L/1/

查看更多
登录 后发表回答