js 自制图片上传组件 可预览

本文介绍了一个自定义的图片上传组件的实现过程,包括HTML结构、CSS样式和JavaScript交互逻辑,展示了如何利用FileReader API预览用户上传的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图:
在这里插入图片描述在这里插入图片描述

html部分
<div class="chose-pic-box">
    <div class="show-pic">
        <p class="upload-text">上传海报</p>    <!-- 未上传时显示的文字提示 -->
        <img src="../img/upload-pic.png" alt="" class="upload-icon">    <!-- 未上传时显示的提示图片 -->
        <img src="" alt="" id="the-picture">    <!-- 上传的图片显示位置,起初为空或隐藏 -->
    </div>
    <input type="file" accept="image/jpg,image/jpeg,image/png,image/PNG" class="chose-pic-btn"
           onchange="uploadPicture()">    <!-- 上传图片,在改变时调用显示图片的方法 -->
</div>
css部分
.chose-pic-box{
    width: 200px;
    height: 200px;
    border: 1px solid lightgrey;
    padding: 5px;
    margin-left: 15px;
    border-radius: 3px;
    position: relative;
}

.chose-pic-btn{
    width: 100%;    /* 让其铺满整个框,点击框内任意地方都可以选择文件 */
    height: 100%;
    opacity: 0;    /* 让其透明不显示,显示自己设置的样式 */
    cursor: pointer;
    position: absolute;    /* 相对最外面的框位置固定 */
    top: 5px;
    left: 5px;
}

// 自己设置的样式
.show-pic{
    width: 100%;
    height: 100%;
    border: 2px dashed lightgrey;
    text-align: center;
    font-size: 2.0rem;
    color: #9d9d9d;
}

.show-pic .upload-text{
    margin-top: 30px;
}

// 显示上传的图片,固定大小
.show-pic #the-picture{
    display: inline-block;
    width: 100%;
    height: 100%;
}
js部分
function uploadPicture() {
    var theFile = new FileReader();
    var f = document.getElementsByClassName("chose-pic-btn")[0].files[0];
    var thePic = document.getElementById("the-picture");
    theFile.onload = function () {
        thePic.src = this.result;
        $(".upload-text").css("display", "none");  //隐藏未上传时的文字和图片
        $(".upload-icon").css("display", "none");
    };
    if (f) {
        theFile.readAsDataURL(f);
    }
}

FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件,具体内容及使用方法可参考MDN文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值