原生js实现上传图片控件

一、修改原生 input 样式

<div com.cn/tag/class" target="_blank">class="card">
    <input id="upload" type="file" accept=".jpg" />
    <div class="view">
        <!-- 上传成功后 -->
        <div id="imgContainer" class="img-container">
            <img id="img" />
            <!-- 鼠标移入展示 查看 与 删除 操作 -->
            <div class="img-mask">
                <span id="showImg">查看</span>
                <span id="delImg">删除</span>
            </div>
        </div>
        <!-- 上传成功前 -->
        <span id="icon">+</span>
    </div>
</div>

css 样式

.card {
    position: relative;
    width: 200px;
    height: 140px;
    padding: 5px;
    margin-right: 20px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    margin: 300px auto;
}
.card input {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}
.card .view {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.card .view #icon {
    display: inline-block;
    font-size: 30px;
}
.card .view .img-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: none;
}
.img-container img {
    width: 100%;
    height: 100%;
}
.img-container .img-mask {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    background: rgba(0, 0, 0, .3);
    transition: all .5s ease;
    display: flex;
    justify-content: center;
    align-items: center;
}
.img-container:hover .img-mask {
    opacity: 1;
}
.img-mask span {
    color: #fff;
    margin: 0 10px;
    cursor: pointer;
}