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

来源:互联网 发布:怎样开淘宝账号 编辑:程序博客网 时间:2024/06/06 15:01

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

这里写图片描述

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

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 0