JS:上传时图片预览(input:type="file" :)

一、准备工作

1.默认素材:Img_add.png

2 使用window.FileReader :预览

二、以默认图片覆盖input:type="file"元素。浏览图片,实现预览 

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>测试图片</title>
    </head>
    <body>
        <div class="FileDiv"  style="position:relative;left:0;top:0;width:150px; height:150px;" >
            <input style="position:absolute;width:0px; height:0px;display:none;" type="file" accept="image/*" id="file" name="file" onchange="showPreview(this)" />
            <img style="position:absolute;left:0;top:0;width:150px; height:150px;z-index:0;" width="150" height="150" id="portrait" src="Images/Img_add.png" onclick="document.getElementById('file').click()"> 
         </div>
         
   
    </body>
</html>

 
<script type="text/javascript">
     function showPreview(source) {
        var file = source.files[0];
        if (!/image\/\w+/.test(file.type)) {
            alert("请确保文件为图像类型");
            return false;
        }
        if (window.FileReader) {
            var fr = new FileReader();
            fr.onloadend = function (e) {
                document.getElementById("portrait").src = e.target.result;
                document.getElementById("portrait").style.display = " inline-block";
            };
            fr.readAsDataURL(file);
        }
    }
</script>

  

猜你喜欢

转载自www.cnblogs.com/July-/p/10063843.html