前端页面上传图片并回显

版权声明:转载请注明出处!!谢谢!! https://blog.csdn.net/weixin_43474398/article/details/90768884

只用前端js。jquery。

前端html

<style>

    .uploadImgBtn {
        border: black solid 1px;
        width: 200px;
        height: 200px;
        cursor: pointer;
        position: relative;
        background-image: url("12.jpg");
        -webkit-background-size:  cover;
        background-size: cover;
    }
    .uploadImgBtn .uploadImg {
        position: absolute;
        right: 0;
        top:0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
    }
    /*这是一个用做回显的盒子的样式*/
    .pic{

        width: 100px;
        height: 100px;
    }
    .pic img {
        border: saddlebrown solid 2px ;
        width: 200px;
        height: 200px;
    }
</style>

别忘了引入js文件

 <script>
    $(document).ready(function(){
        $("#uploadImgBtn").click(function(){
            var $input = $("#file");
            console.log($input)
            $input.on("change" , function(){
                console.log(this)
                var files = this.files;
                var length = files.length;
                console.log("选择了"+length+"张图片");
                //3、回显
                $.each(files,function(key,value){
                    //每次都只会遍历一个图片数据
                    var div = document.createElement("div"),
                        img = document.createElement("img");
                    div.className = "pic";

                    var fr = new FileReader();
                    fr.onload = function(){
                        img.src=this.result;
                        div.appendChild(img);
                        document.body.appendChild(div);
                    }
                    fr.readAsDataURL(value);
                })

            })

            //4、我们把当前input标签的id属性remove
            $input.removeAttr("id");
            //我们做个标记,再class中再添加一个类名就叫test
            var newInput = '<input class="uploadImg test" type="file" name="file" multiple id="file">';
            $(this).append($(newInput));

        })

    })

</script>

效果

在这里插入图片描述
在这里插入图片描述
不明白的call我。。共同进步。。

猜你喜欢

转载自blog.csdn.net/weixin_43474398/article/details/90768884
今日推荐