Magnific Popup上传图片预览

时间:2016-01-29 09:36:37

标签: image file-upload popup filereader magnific-popup

我正在使用Magnific弹出窗口显示上传表单,用户可以在提交表单之前选择要上传和预览的多个图片,我让用户预览图片,并在点击图片时在图片下方添加输入它输入标题和替代它,这是我的代码......

(function() {
            if ($("a.uploadMediaImageForm").length) {
                $("a.uploadMediaImageForm").magnificPopup({
                    type: 'inline',
                    preloader: false,
                    closeOnBgClick: false,
                    enableEscapeKey: false,
                    focus: '#name',

                    removalDelay: 500, //delay removal by X to allow out-animation

                    // When elemened is focused, some mobile browsers in some cases zoom in
                    // It looks not nice, so we disable it:
                    callbacks: {
                        beforeOpen: function() {

                            if ($(window).width() < 700) {
                                this.st.focus = false;
                            } else {
                                this.st.focus = '#name';
                            }

                            this.st.mainClass = this.st.el.attr('data-effect');
                        },

                        open: function() {

                            if ($("input#imageUpload").length) {

                                $("input#imageUpload").on('change', function() {

                                    //Get count of selected files
                                    var countFiles = $(this)[0].files.length;

                                    var imgPath = $(this)[0].value;
                                    var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
                                    var previewHolder = $("ul.imagePreview");
                                    previewHolder.empty();

                                    if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
                                        if (typeof(FileReader) != "undefined") {

                                            //loop for each file selected for uploaded.
                                            for (var i = 0; i < countFiles; i++) {

                                                var reader = new FileReader();
                                                reader.onload = function(e) {

                                                    $("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
                                                }

                                                previewHolder.show();
                                                reader.readAsDataURL($(this)[0].files[i]);
                                            }

                                        } else {
                                            alert("This browser does not support FileReader.");
                                        }
                                    } else {
                                        alert("Please select only images");
                                    }
                                });
                            } //Image upload preview

                            if($("ul.imagePreview").length) {
                                $("ul.imagePreview").on("click", "li", function(event) {
                                    if($(this).hasClass("selected")) {
                                        $(this).removeClass("selected");
                                        $(this).find("div").remove();
                                    } else {
                                        $(this).addClass("selected");
                                        $(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
                                    }
                                });

                                $("ul.imagePreview").on("click", "div", function(event) {
                                    event.stopPropagation();
                                });
                            }//add form when clicked on an image
                        },

                        beforeClose: function() {
                            // $("ul.imagePreview").empty();
                            var countFiles = "";
                            var imgPath = "";
                            var extension = "";
                            var previewHolder = $("ul.imagePreview");
                            previewHolder.empty();
                        }
                    },

                    midClick: true // allow opening popup on middle mouse click. Always set
                });
            }
        })(); //popup Forms and Uploads
div.uploadPopup {
    width: 80%;
    margin: auto;
    background: white;
    position: relative;
    padding: 40px;
}

label {
    width: 100%;
    margin-bottom: 20px;
    clear: both;
}

ul.imagePreview {
    width: 100%;
    clear: both;
    display: block;
}

ul.imagePreview li {
    width: 100%;
    display: block;
    margin-bottom: 20px;
    max-height: 150px;
    cursor: pointer;
}

ul.imagePreview li.selected {
    max-height: auto;
}

ul.imagePreview li img {
    max-height: 150px;
    display: block;
    margin: auto;
}
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
<a href="#uploadMediaImageForm" class="uploadMediaImageForm" data-effect="mfp-3d-unfold">Upload Media</a>

<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
    <form action="#">

        <label class="upload">
            <span>Upload Images</span>
            <input id="imageUpload" type="file" multiple>
        </label>

        <ul class="imagePreview">

        </ul>
    </form>
</div>

现在一切正常,但是当我关闭弹出窗口并再次重新打开它时,图像预览器出现了错误,它复制了我选择的图像,有时甚至不显示图像我在结束前选择的最后一张图片。

我尝试在关闭弹出窗口之前设置所有变量并清除图像预览ul元素,但这没有帮助。

我需要你的帮助,我在这里做错了什么?

修改

我给表单本身写了一个“fileForm”的id,并尝试重置整个表单并清空ul.imagePreview,然后用这段代码关闭弹出窗口...

$("#fileForm")[0].reset();
$("ul.imagePreview").empty();

但是仍然没有运气,它仍然复制了我在关闭弹出窗口并再次打开它后第二次上传的任何图像!!

需要帮助。

1 个答案:

答案 0 :(得分:2)

您正在为同一事件绑定越来越多的侦听器:

即使弹出窗口关闭,您的表单也始终存在于您的文档中,您只需在大多数时间隐藏它(使用类mfp-hide)。

每次打开弹出窗口时,回调&#34;打开&#34;被调用,它将函数绑定到输入的更改事件,此回调执行预览。

但是如果你打开两次弹出窗口,它会再次将相同的函数绑定到同一个输入上的同一个事件。这就是你重复的原因:代码被调用两次。

将所有绑定移到回调之外,以便它们完成一次:

&#13;
&#13;
 (function() {

    if ($("input#imageUpload").length) {
        $("input#imageUpload").on('change', function() {

            //Get count of selected files
            var countFiles = $(this)[0].files.length;

            var imgPath = $(this)[0].value;
            var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            var previewHolder = $("ul.imagePreview");
            previewHolder.empty();

            if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
                if (typeof(FileReader) != "undefined") {

                    //loop for each file selected for uploaded.
                    for (var i = 0; i < countFiles; i++) {

                        var reader = new FileReader();
                        reader.onload = function(e) {

                            $("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
                        }

                        previewHolder.show();
                        reader.readAsDataURL($(this)[0].files[i]);
                    }
                } else {
                     alert("This browser does not support FileReader.");
                }
            } else {
                alert("Please select only images");
            }
        });
    } //Image upload preview

    if($("ul.imagePreview").length) {
        $("ul.imagePreview").on("click", "li", function(event) {
            if($(this).hasClass("selected")) {
                $(this).removeClass("selected");
                $(this).find("div").remove();
            } else {
                $(this).addClass("selected");
                $(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
            }
        });

        $("ul.imagePreview").on("click", "div", function(event) {
            event.stopPropagation();
        });
    }//add form when clicked on an image

    if ($("a.uploadMediaImageForm").length) {
        $("a.uploadMediaImageForm").magnificPopup({
            type: 'inline',
            preloader: false,
            closeOnBgClick: false,
            enableEscapeKey: false,
            focus: '#name',

            removalDelay: 500, //delay removal by X to allow out-animation

            // When elemened is focused, some mobile browsers in some cases zoom in
            // It looks not nice, so we disable it:
            callbacks: {
                beforeOpen: function() {

                    if ($(window).width() < 700) {
                        this.st.focus = false;
                    } else {
                        this.st.focus = '#name';
                    }

                    this.st.mainClass = this.st.el.attr('data-effect');
                },

                beforeClose: function() {
                    ///$("ul.imagePreview").empty();
                    var countFiles = "";
                    var imgPath = "";
                    var extension = "";
                    var previewHolder = $("ul.imagePreview");
                    previewHolder.empty();
                    $("#fileForm")[0].reset();
                }
            },

            midClick: true // allow opening popup on middle mouse click. Always set
        });
    }
})(); //popup Forms and Uploads
&#13;
div.uploadPopup {
    width: 80%;
    margin: auto;
    background: white;
    position: relative;
    padding: 40px;
}

label {
    width: 100%;
    margin-bottom: 20px;
    clear: both;
}

ul.imagePreview {
    width: 100%;
    clear: both;
    display: block;
}

ul.imagePreview li {
    width: 100%;
    display: block;
    margin-bottom: 20px;
    max-height: 150px;
    cursor: pointer;
}

ul.imagePreview li.selected {
    max-height: auto;
}

ul.imagePreview li img {
    max-height: 150px;
    display: block;
    margin: auto;
}
&#13;
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
<a href="#uploadMediaImageForm" class="uploadMediaImageForm" data-effect="mfp-3d-unfold">Upload Media</a>

<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
    <form action="#" id="fileForm">

        <label class="upload">
            <span>Upload Images</span>
            <input id="imageUpload" type="file" multiple>
        </label>

        <ul class="imagePreview">

        </ul>
    </form>
</div>
&#13;
&#13;
&#13;