layui剪裁插件cropper一个页面调用多次问题解决

原创
2020/04/07 18:50
阅读数 886

问题:在一个页面调用多个cropper剪裁插件时,我们会发现虽然每个id我们都声明了,但当我们点击相应的区域时,cropper剪裁区域会弹出来,但选好后点击保存,我们会发现剪裁图片只会出现在最后一个声明的id那里。虽然我们可以在每个区域那里设置一个点击事件,通过改变相应的值来告诉cropper图片显示在那个位置,但那样很麻烦,代码重复利用率很低

解决方法如下:

var uploadList = new Array();
	uploadList.push({"name": "upload", "uploadCount": 0, "url": ""});
	uploadList.push({"name": "upload2", "uploadCount": 0, "url": ""});
	uploadList.push({"name": "upload3", "uploadCount": 0, "url": ""});
function layuiInit() {
    layui.use(['element', 'form', 'layer', 'upload'], function(){
        var element = layui.element;
        var form = layui.form;
        var layer = layui.layer;
        var upload = layui.upload;
        
        upload.render({
            elem: 'upload, #upload2, #upload3',
            url: path + "fileManager/uploadImg",// 上传接口
            done: function(res) {
                $this = this.item;
                var name = $this.attr('id');
                var obj = uploadList.filter((u) => {
                    return u.name == name;
                })[0];
                // 删除上次上传但还未提交的图片
                if(obj.uploadCount > 0) {
                    $.ajax({
                        type: "get",
                        url: path + "fileManager/deletePicture?url=" + obj.url,
                        contentType: "application/x-www-form-urlencoded;charset=utf-8",
                        success: function() {}
                    });
                }
                // 赋值
                $this.attr("value", res[0]);
                // 回显预览图片
                $this.css({
                    "background-image": "url(" + path + "fileManager/showPicture?url=" 
                    + res[0] +")"
                });
                // 拼接(功能需求:upload只有一张图片,不需要拼接,其它的需要)
                var $input = $this.parent().prevAll('input');
                var value = $input.val();
                if(name == 'upload' || value == "") {
                    $input.val(res[0]);
                } else {
                    $input.val($input.val() + "," + res[0] + ",");
                }
				
                obj.uploadCount++;
                obj.url = res[0];
            },
            error: function(){}
        }); 
    });
}

传送门:

layui剪裁插件cropper下载地址及使用手册: https://fly.layui.com/extend/croppers/

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部