欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

input type="file"时的样式修改以及图片预览

程序员文章站 2022-04-29 15:05:54
...

之前公司的垃圾前端连这个都不会弄,直接自己动手,直接上代码

html

<div class="head-img">
    <img src="照相机.png" id="my-img" style="width: 200px;height: 200px">
    <input type="file" id="img-upload" accept="image/*" />
</div>

css

    .head-img {
        text-align: center;
        position: relative;
    }

    #img-upload {
        opacity: 0;
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0;
        left: 50%;
        margin-left: -100px;
    }

js

$(document).ready(function() {
    $(document).on('change', "#img-upload", function(event) {
        var _file = $(this);
        var _fileObj = _file[0];
        var windowURL = window.URL || window.webkitURL;
        var dataURL = windowURL.createObjectURL(_fileObj.files[0]);
        $(document).find('#my-img').attr('src', dataURL);
    });
});