jQuery+layui will take you to upload, delete and zoom in preview pictures

jQuery is old. Can you still fight?

Recently, I have often seen this question and the answers of various front-end developers. The author thinks that in the era of large front-end, jQuery is still hot today with project modular development. Why do you say so? Although many companies now use Vue and React frameworks for project development, for old projects developed using jQuery in the past, jQuery technology stack should still be used to repair problems and realize new requirements. However, it has to be said that this is a process of transformation from jQuery to Vue and React.

When it comes to jQuery, we need to mention BootStrap and layui framework. Both are the products of the jQuery era. They complement jQuery and have developed many excellent projects. Although layui closed its official website in October this year, it continues to be maintained on gitee (code cloud). I remember that the author was excited when I first saw this news, I have to sigh that the times are changing and technology is progressing!

This paper uses jQuery, layui and BootStrap to write a case that supports multi picture upload, single / multi picture deletion and local zoom in for preview. In the actual project, if picture upload is involved, it is basically inseparable from these functions. Since it is a repeated demand, you can take it out and write a case for future use. I hope readers will enjoy it.

The files referenced by the case are as follows, which are all referenced external cdn resources, so the code written in this case can be directly copied to the local run to see the effect.

<!-- introduce bootstrap of css file -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- introduce bootstrap of js file -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
    <!-- introduce jQuery file -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <!-- introduce layui of css file -->
    <link rel="stylesheet" href="https://layui.itze.cn/layui-v2.6.8/layui/css/layui.css">
    <!-- introduce layui of js file -->
    <script src="https://layui.itze.cn/layui-v2.6.8/layui/layui.js"></script>

The style files of the case are as follows, which are the style codes of the imgContainer picture box.

    <style>
        .imgContainer div {
            position: relative;
            display: inline-block;
        }
        
        .imgContainer img {
            width: 200px;
            height: 200px;
            margin: 10px;
        }
        /* The X delete button of each picture is realized by positioning */
        
        .imgContainer span {
            position: absolute;
            top: 5%;
            right: 5%;
            background-color: pink;
            padding: 1px;
            display: none;
            cursor: pointer;
        }
    </style>

The case layout of this article is the BootStrap framework used. In daily development, using the BootStrap framework can help us save a lot of HTML and CSS code. Of course, the premise is to know what classes the BootStrap framework provides for us to use directly.

    <div class="container-fluid">
        <div class="row form-table-row">
            <div class="col-sm-6 form-table-col">
                <div class="form-group form-flex">
                    <button class="btn btn-primary" id="selectFile">Select file</button>
                    <button class="btn btn-primary" id="deleteImg">Delete all</button>
                </div>
            </div>
        </div>
        <div class="row form-table-row">
            <div class="col-sm-6 form-table-col">
                <div class="form-group form-flex">
                    <!--  imgContainer The box is used to preview the picture  -->
                    <div class="imgContainer" style="">
                    </div>
                </div>
            </div>
        </div>
        <div class="row form-table-row">
            <div class="col-sm-6 form-table-col">
                <div class="form-group form-flex">
                    <div class="" style="">
                        <!-- Initially hide the upload picture button and display it after selecting a picture -->
                        <button class="btn btn-primary" id="uploadImg" style="display: none">upload</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

The following is the key JS code of this case. Although it is not complex, in the process of its implementation, the author found that there are still some details to pay attention to, such as single / multi picture upload, preview function, single picture deletion function, etc., because the code comments are written in detail. If readers have doubts, they can see the official documents of the layui framework.

    <script>
        var uploadInst;
        layui.use('upload', function() {
            var upload = layui.upload;
            //Execution instance
            uploadInst = upload.render({
                elem: '#selectFile',
                // url: '/upload /', / / the upload interface is configured according to your actual situation
                auto: false, // Turn off automatic upload after selecting files
                acceptMime: 'image/*',
                choose: function(obj) {
                    var files = obj.pushFile();
                    //Read ahead local file example, ie8 is not supported
                    obj.preview(function(index, file, result) {
                        // Each time you select a picture, add a div to the imgContainer box
                        $('.imgContainer').append(`<div><img src="${result}"><span onClick="deleteOne(this)">X<span></div>`);
                        // Display upload button
                        $('#uploadImg').css('display', 'inline-block');
                        // Listen and delete all pictures
                        $('#deleteImg').on('click', function() {
                            // delete files[index]; //  Delete files in the file queue
                            $('.imgContainer')[0].innerHTML = '';
                            uploadInst.config.elem.next()[0].value = ''; // Allow overwrite to select the same file
                            if ($('.imgContainer img').length == 0) {
                                $('#uploadImg').css('display', 'none');
                            }
                        });
                        // When the mouse passes the box where the picture is located, the X in the upper left corner is displayed
                        $('.imgContainer div').on('mouseenter', function(e) {
                            $($(this)[0].children[1]).css('display', 'inline-block');
                        });
                        // When the mouse leaves the box where the picture is located, the X in the upper left corner is hidden
                        $('.imgContainer div').on('mouseleave', function(e) {
                            $($(this)[0].children[1]).css('display', 'none');
                        });
                        // Monitor picture click events
                        $('.imgContainer div img').on('click', function() {
                            layer.open({
                                type: 4,
                                tips: 1, // Pop up layer below
                                content: ['<img style="width:400px;height:400px" src="' + $(this)[0].src + '">', this],
                                shade: 0, // Do not show mask
                                area: ['450px', '430px'], // Set width and height
                                time: 1000 // Automatically hide pop-up layer after 1 second
                            });
                        })
                    });
                },
                done: function(res) {
                    //Upload completion callback
                },
                error: function() {
                    //Request exception callback
                }
            });
        });
        // Delete a single photo
        function deleteOne(that) {
            uploadInst.config.elem.next()[0].value = '';
            $($(that)[0].parentNode)[0].innerHTML = '';
            if ($('.imgContainer img').length == 0) {
                $('#uploadImg').css('display', 'none');
            }
        }
    </script>

The above is all about the content of this blog. I hope all readers can try it by themselves. Just like now, the author sits in front of the computer and writes the code of this case. A group of people outside are eating barbecue and making fun. We insist on learning during other people's fun time. I believe Kung Fu pays off. If readers find that there are errors in the code or they have better practices, they are welcome to leave a message in the comment area for discussion. If they think it's good, they can like it and forward it to more people. Please indicate the source for reprint. Thank you~

Author's official account: Art of program, welcome to explore more art of procedure together.

Keywords: Javascript JQuery Layui

Added by spudmclard on Thu, 16 Dec 2021 01:12:46 +0200