前端案例--图片上传功能

实现简单的图片上传功能,显示选择图片名和预览图片效果!

这里写图片描述

涉及知识点:表单美化、正则表达式、文件对象

HTML代码:

<div id="container">
        <div id="upload">
            <!-- 图片上传 -->
            <a><input type="file" name="" onchange="uploadFace(this);"></a>
            <!-- 文件名 -->
            <input type="text" name="" id="fileName">
        </div>
        <!-- 图片预览区 -->
        <div id="face"><img id="preview" alt=""></div>
    </div>

css代码:

@font-face { 
        font-family:"迷你简趣味";
        src: url("迷你简趣味.ttf");
        } 
    body,html{
        margin:0;padding:0;
        width:100%;height:100%;
        background: #3C8FC1;
    }
    #container{
        width:900px;height:350px;
        background:url("images/bg.jpg") no-repeat;
        margin:auto;
        position: relative;
        top:20%;

    }
    #upload{
        background:#fff;
        height:80px;
        border-radius:5px;
        padding:10px;
        position:absolute;
        top:60%;
        left:5%;
    }
    #upload a{
        display: inline-block;
        width:80px;height:82px;
        border:1px solid #ccc;
        border-radius:6px 0 0 6px; 
        background:url("images/icon.png") no-repeat center center;
        float:left;
    }
    #upload a:hover{background-color: #ccc;}
    #upload input#fileName{
        width:250px;height:80px;line-height: 40px;
        border:1px solid #ccc;
        border-radius:0 6px 6px 0;
        border-left:none;
        font-family: "迷你简趣味.ttf";
        color:#ccc;
        font-size:20px;
        padding-left: 5px;
    }
    #upload a input{
        width:80px;height:80px;
        opacity:0;
        cursor:pointer;
    }
    #face{
        width:285px;height:285px;
        position:absolute;
        top:31px;right:56px;
        border-radius:10px;
        overflow:hidden;
    }
    #face img{
        width:285px;height:285px;
    }

javascript代码:

//图片更换时候调用
    function uploadFace(sender){
        //判断选择的是否是图片
        if(!sender.value.match(/.jpg|.gif|.jpeg|.bmp|.png/i)){
            alert("请选择图片文件!");
        }else{
            //将文件按名字放置在该input中
            var filename=document.getElementById("fileName");
            filename.value=sender.files[0].name;
            //将选择的图片显示在预览元素中
            var preview=document.getElementById("preview");
            preview.src=window.URL.createObjectURL(sender.files[0]);
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值