給<input type="file">增加樣式

方健發表於2014-12-05

參考:
1. http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
2. http://pan.baidu.com/s/1F9Uqy
3. http://stackoverflow.com/questions/4909228/style-input-type-file

這篇文章用的是bootstrap。我用的是semantic-ui也差不多

1.搞個button出來

<span class="ui fluid button btn-file">
     <span id="buttonLabel">選擇圖片</span> <input type="file" name="img">
</span>

2. 搞個CSS

.btn-file {
    position: relative;
    overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}

3. 搞個JS

$(document).on('change', '.btn-file :file', function() {
    var input = $(this),
        numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
    input.trigger('fileselect', [numFiles, label]);
});

4. JS要這麼用

$(document).ready( function() {
    $('.btn-file :file').on('fileselect', function(event, numFiles, label) {
        console.log(numFiles);
        console.log(label);
        $("#buttonLabel").text(label);
    });
}); 

相關文章