H5照片预览

效果展示http://sandbox.runjs.cn/show/vvxiaalz

代码:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <style type="text/css">

        .imgCom{

            width: 300px;

            height: 300px;

            border:1px solid #000;

        }



        .imgCom > img{

            width: 100%;

            height: 100%;

        }



    </style>

</head>

<body>

    <input type="file">

    <div class="imgCom" id="imgCom"></div>

    

    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>

    <script type="text/javascript">

        function previewA(file) {

            var img = new Image(), url = img.src = URL.createObjectURL(file);//获取url地址

            var $img = $(img);

            img.onload = function() {

                URL.revokeObjectURL(url);//释放内存

                $('#imgCom').empty().append($img)

            }

            

            console.log(url);

        }

        function previewB(file) {

            var reader = new FileReader();//创建FileReader对象

            reader.onload = function(e) {

                var $img = $('<img>').attr("src", e.target.result)

                $('#imgCom').empty().append($img)

            }

            reader.readAsDataURL(file)

        }

         

        $('[type=file]').change(function(e) {

            var file = e.target.files[0],//事件目标

            val      = $(this).val(),

            reg      = /\.(png|jpg|gif|bmp)$/;



            if( reg.test(val) ){

                // previewA(file)

                previewB(file)

            }else{

                alert('选择正确格式的图片');

            }

        })

    </script>



</body>

</html>

 

你可能感兴趣的:(H5)