<input type=“flie“>上传文件

使用<input type="file">和JS实现上传图片操作。

1.先写出css样式,这里采用了响应式布局,写的移动端样式。

<style>
        * {
            padding: 0;
            margin: 0;
            list-style: none;
        }
        html {
            font-size: 62.5%;
        }
        body {
            text-align: center;
        }
        .alert {
            padding-top: 60px;
            font-size: 2.4rem;
            display: none;
        }
        .container {
            height: 100vh;
            background-color: deepskyblue;
            overflow: hidden;
        }
        @media screen and (min-width:968px) {
            /* 非移动端 */
            .alert {
                display: block;
            }
            .container {
                display: none;
            }
        }
        .head_pic {
            width: 100px;
            height: 100px;
            margin: 80px auto;
            border-radius: 50%;
            /* 插入一张默认图片 */
            background-image: url(https://img0.baidu.com/it/u=3822250181,2054335924&fm=253&fmt=auto&app=120&f=JPEG?w=750&h=500);
            background-size: cover;
            background-position: center center;
        }
        input {
            display: block;
            width: 100px;
            height: 100px;
            /* 隐藏上传文件的框,点击图片时仍可上传 */
            opacity: 0;
        }
    </style>

2.html样式

 <p class="alert">请使用移动端打开</p>
    <div class="container">
        <div class="head_pic">
            <input type="file">
        </div>
    </div>

3.js实现上传图片操作

<script>
    //获取input
    var ipt = document.querySelector("input");
    //获取图片显示区域
    var dHeadPic = document.querySelector(".head_pic");
    //onchange事件,事件会在域的内容改变时发生
    ipt.onchange = function (e) {
        //选择的图片
        var file = this.files[0];
        //创建一个文件读取对象
        var reader = new FileReader();

        //onload 事件会在页面或图像加载完成后立即发生。
        reader.onload = function () {
            //读取完成后执行
            // reader.result读取文件的信息内容
            dHeadPic.style.backgroundImage = `url(${reader.result})`;
        }
        //调用函数
        reader.readAsDataURL(file);
    }

这样一个图片上传操作就完成了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值