多张图片上传(设置主图,删除图片)---简化js拼接

描述:后台商品编辑时,页面:上传图片,设置图片主图,以及删除图片,后台:保存图片到图片服务器,返回完整目录

1.页面 html:

    <div title="图片">
          <div class="decimg">
             <spn style="font-weight: bold;font-size:15px;">商品图片</spn>(最多可添加10张图片,建议图片尺寸600*600px,大小≤6MB,支持JPG、PNG、JPEG)
             <span id="imgcount" style="margin-left:50px;font-weight: bold;">共 0 张</span>
          </div>
            <ul  id="content" class="imgAll">
            </ul>
           <div class="imgAll">
            <div class="upimg">
                <img src="" id="smallImg"/>
                <span class="desc"><a href="javascript:fixUpload(1)">多张上传</a>【列表图片】</span>
            </div>
            <div class="addimg">
            </div>
          </div>
     </div>
2.样式:

<style type="text/css">
.decimg{margin:10px 10px}
.imgAll{}
.addimg img{width: 150px;height: 140px;border: 0px;cursor: pointer;}
.upimg { float:left;width: 150px;height: 140px;margin-left:50px; position:relative;}
.upimg img{width: 150px;height: 140px;border: 0px;cursor: pointer;}
.upimg:hover .desc{display: block}
.upimg .desc{display: none;font-size: 12px;background: #111;filter: alpha(opacity=60);color: White;opacity: .6;
                   position: absolute;bottom:0px;
                   padding: 10px;margin: 0;width: 130px;border-top: 1px solid #999;}
.upimg a,.upimg a:hover,.upimg a:link,.upimg a:visited{color: White;}

.upimg .del-img
{
  position: absolute;
  padding: 0 6px;
  top: 0;
  right: 0;
  font-size: 22px;
  margin: 0;
  border: none;
  background-color: transparent;
  display: none;
}
.upimg:hover .del-img
{
    display: block;
}
</style>
3.js 脚本:---简化js拼接

要点:

a.简化js拼接--扩展

    String.prototype.tpl = function (obj) {
        return this.replace(/\{\$(\w+)\}/g, function (_, bb) {
            try {
                var data = eval("obj." + bb);
                return data === undefined ? eval(bb) : data;
            } catch (e) {
                try { return eval(bb); } catch (e) { return _; }
            }
        });
    }

使用:

var tpl=$('#tpl').html(); //定义dom 设置参数:id="smallImg{$Id}_{$sort}" path="{$imgUrl}"

var proinfo={}; // 对象,对象字段为 定义的 参数 。

var temp += tpl.tpl(proinfo); //替换参数

2. js 属性,用法

将后一个集合对象加入到前一个集合对象中 ,此方法支持ie1.5以上版本

Array.prototype.push.apply(oldList,data);// list 集合对象,注意 和数组 区别开

---对象系列化和反系列化

var oldList=JSON.parse(oldimglist);

var ttt = JSON.stringify(listnew);

3.jquery dom操作,获取和赋值

 $("img[sort='0']").parent().find('.desc').css("display","block");   //找 (属性sort=0的img标签)的父标签 下 样式为desc 的标签,修改其样式
 $("img[sort='0']").parent().find('a').html('主图图片').attr("href","#");//设置主图且不跳转

4.逻辑

因后台建表:sort 是排序字段,且sort=0时 为主图,前端图片数据以json 格式保存到隐藏控件,提交时传至后台直接转化为对象 保存至数据库,

所以js 操作 设置主图,删除图片时,除了要操作dom元素 属性的变化,还要对 对象集合进行操作。

代码如下:

   <script id="tpl" type="text/tpl">
        <li class="upimg" οnmοuseοver="funover(this)" οnmοuseοut="funout(this)">
            <img src="{$srcimgUrl}" id="smallImg{$Id}_{$sort}" path="{$imgUrl}" sort="{$sort}"/>
            <span class="desc"><a href="javascript:setMainImg('smallImg{$Id}_{$sort}')">设置主图</a>【列表图片】</span>
            <button οnclick="del_goodsimg(this,'smallImg{$Id}_{$sort}');" class="del-img" type="button">×</button>
        </li>
   </script>
<script type="text/javascript">
    var serverPath='<%=System.Configuration.ConfigurationManager.AppSettings["xjmainUrl"] %>';
    var ueoption = { toolbar: [
            'source | undo redo | emotion | bold italic underline strikethrough | forecolor backcolor | removeformat |',
            'link unlink | selectall cleardoc | paragraph fontfamily fontsize |',
            'justifyleft justifycenter justifyright justifyjustify |',
            'image insertvideo  | map |',
            'fullscreen'],
        autoClearinitialContent: false,
        wordCount: false,
        minFrameHeight: 80,
        maxFrameHeight: 80,
        elementPathEnabled: false,
        zIndex: 1,
        charset: "utf-8",
        initialStyle: 'p{font-size: 12px;line-height:15px; }',
        //imageUrl:URL+"../../../../../net/imageUp.ashx",       
        //imagePath:URL + "../../../../../net/",                
        imageUrl:URL+"../../../../../UMupload/imageUp.ashx",//图片上传提交地址
        imagePath: serverPath,//图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
    };
    var ue = UM.getEditor('txtContent', ueoption);

    var _id = '<%=Request["id"]%>';
    var $content = $('#content');
    //简化js拼接
    String.prototype.tpl = function (obj) {
        return this.replace(/\{\$(\w+)\}/g, function (_, bb) {
            try {
                var data = eval("obj." + bb);
                return data === undefined ? eval(bb) : data;
            } catch (e) {
                try { return eval(bb); } catch (e) { return _; }
            }
        });
    }
    $(function () {
        var dt = new Date();
        var sort = dt.format('yyMMddHHmmssS');
        //var sort = dt.getTime().toString(32);
        $('#sort').val(sort);
        proChange();
        $('#TypeId').combotree
            ({ url: '/ajax.ashx?className=mallBasic&methodName=GetPageSync&state=closed',
                valueField: 'id',
                textField: 'text',
                required: true,
                editable: false,
                onSelect: function (node) {
                    //返回树对象  
                    var tree = $(this).tree;
                    //选中的节点是否为叶子节点,如果不是叶子节点,清除选中  
                    var isLeaf = tree('isLeaf', node.target);
                    if (!isLeaf) {
                        //清除选中  
                        $('#TypeId').combotree('clear');
                    } else {
                        $('#protypeid').val(node.id);
                    }
                },
                onClick: function (node) {
                    //JJ.Prm.GetDepartmentUser(node.id, 'selUserFrom');
                }, //全部折叠
                onLoadSuccess: function (node, data) {
                    // $('#TypeId').combotree('tree').tree("collapseAll");
                }
            });

        if (_id != '') {
            $.post("sessionedajax.ashx?rad=" + new Date().toGMTString(),
                { className: "mallBasic", methodName: "GetProductModel", id: _id }, function (data) {
                    $("#form1").form("reset");
                    ue.setContent(data.info.detail);
                    $('#protypeid').val(data.info.protypeid);
                    $('#TypeId').combotree('setValue', data.info.proTypeName);
                    if (data.proImgList != null && data.proImgList.length > 0) {
                          var temp='' ;
                          var tpl = $('#tpl').html();
                          for (var i = 0; i < data.proImgList.length; i++)
                          {
                             var proinfo=data.proImgList[i];
                             proinfo.srcimgUrl=baseUrl+ proinfo.imgUrl;
                             temp += tpl.tpl(proinfo);
                          }
                          $content.html(temp);
                          var ttt = JSON.stringify(data.proImgList);
                          $("#imgList").val(ttt);
                          $("img[sort='0']").parent().find('.desc').css("display","block");
                          $("img[sort='0']").parent().find('a').html('主图图片').attr("href","#");
                    }
                    if (data.info.proBigtype != 0) {
                        $("#effectiveTime").combobox({ disabled: false }).validatebox({ required: true });
                        $("#salesCount").removeAttr("readonly").validatebox({ required: true });
                    }
                    if (data.info.proBigtype == 2) {
                        $("#bookState").combobox({ disabled: false }).validatebox({ required: true });
                        $("#bookPhone").removeAttr("readonly");
                        $("#boolNote").attr("disabled", false);
                    }
                    $("#form1").form("load", data.info);
                    $("#imgcount").html("共 " + data.proImgList.length + " 张");
                }, "json");
        }
        $('#form1').form({
            url: "sessionedajax.ashx?rad=" + new Date().toGMTString(),
            onSubmit: function (param) {
                param.Id = _id;
                param.className = "mallBasic";
                param.methodName = "ProductSaveInfo";
                return $(this).form('validate');
            },
            success: function (data) {
                alert(data);
                if (data.indexOf("成功") == -1) {
                    top.Notify(data, "info");
                    return;
                }
                top.Notify(data, "correct");
                parent.$("#chcTable").datagrid('reload');
                parent.windowClose();
            }
        });
    });
    function BtnSaveOrUpdate() {
        var txt = ue.getContent();
        if (txt == "") {
            top.Notify("产品详情不能为空!", "info");
            return;
        }
        var hiddfaretempId = $('#hiddfaretempId').val();
        if (hiddfaretempId == null || hiddfaretempId == '0') {
            top.Notify("请选择运费模版!", "info");
            return;
        }
        var str = encodeURIComponent(txt);
        $("#detail").val(str);
        $("#form1").submit();
    }
    function proChange() {
        $('#proBigtype').combobox({
            onChange: function (newValue, oldValue) {
                if (newValue != 0) {
                    $("#effectiveTime").combobox({ disabled: false }).validatebox({ required: true });
                    $("#salesCount").removeAttr("readonly").validatebox({ required: true });
                } else {
                    $("#salesCount").attr("readonly", true).validatebox({ required: false });
                    $("#effectiveTime").combobox({ disabled: true });
                }

                if (newValue == 2) {
                    $("#bookState").combobox({ disabled: false }).validatebox({ required: true });
                    $("#bookPhone").removeAttr("readonly");
                    $("#boolNote").attr("disabled", false);
                } else {
                    $("#bookState").combobox({ disabled: true });
                    $("#bookPhone").attr("readonly", true).validatebox({ required: false });
                    $("#boolNote").attr("disabled", true);
                }
            }
        });
    }
    function fnview() {
        var win = window.open("/Pages/xj/Health/view.aspx"); //("../../xj/Health/view.aspx");
        setTimeout(function () {
            win.fnSetHtml(ue.getContent());
        }, 100);
    }
    function fixUpload(index) {
        var oldimglist=$("#imgList").val();
        var imgCount=0;
        if(oldimglist!="")
        {
           var oldList=JSON.parse(oldimglist);
           imgCount=oldList.length;
        }
        if(imgCount>10)
        {
            top.Notify("最多可添加10张图片");
            return;
        }
        openSimpleWindow('商品图片上传', "UploadLogo.aspx?folder=sc&chc=xjchcWeb&filemodel="+index, { height: 200, width: 350 })
    }
    var baseUrl = '<%=System.Configuration.ConfigurationManager.AppSettings["xjmainUrl"] %>';
    function upLoadSuccess(path, data) {
        var oldimglist=$("#imgList").val();
        var oldList=null;
        var temp="";
        if(oldimglist!="")
        {
            oldList=JSON.parse(oldimglist);
            //temp=$content.html();
        }
        var tpl = $('#tpl').html();
        if (data != null && data.length > 0)
        {
            var oldCount=0;
            if(oldList!=null&&oldList.length>0)
            {
                oldCount=oldList.length;
                for (var i = 0; i < oldList.length; i++)
                {
                    var proinfo= oldList[i];
                    if(!proinfo.Isdeleted)
                    {
                        temp += tpl.tpl(proinfo);
                    }
                }
            }
            for (var i = 0; i < data.length; i++)
            {
                var proinfo= data[i];
                proinfo.srcimgUrl=baseUrl+ proinfo.imgUrl;
                proinfo.sort=oldCount+proinfo.sort;
                if(proinfo.sort<10)
                {
                  temp += tpl.tpl(proinfo); //替换参数
                }
            }
            $content.html(temp); //dom填充赋值
            var listnew=null;
            if(oldCount>0)
            {
               Array.prototype.push.apply(oldList,data);//将后一个集合对象加入到前一个集合对象中 ,此方法支持ie1.5以上版本
               listnew= oldList;
            }else
            {
                listnew=data;
            }
            var ttt = JSON.stringify(listnew);
            $("#imgList").val(ttt);
        }
        $("img[sort='0']").parent().find('.desc').css("display","block");
        $("img[sort='0']").parent().find('a').html('主图图片').attr("href","#");
        windowClose();
    }
    //删除图片
    function del_goodsimg(p,imgid)
    {
        p.parentElement.remove();//界面元素删除
        var oldimglist=$("#imgList").val();
        if(oldimglist!="")
        {
           var oldList=JSON.parse(oldimglist);
           if(oldList!=null&&oldList.length>0)
           {
                for (var i = 0; i < oldList.length; i++)
                {
                    var proinfo= oldList[i];//
                    var oid="smallImg"+proinfo.Id+"_"+proinfo.sort;
                    if(imgid==oid)
                    {
                        proinfo.Isdeleted=true;
                        break;
                    }
                }
           }
           var ttt = JSON.stringify(oldList);
           $("#imgList").val(ttt);
        }
    }
    function setMainImg(id)
    {
        var mid=$('#'+id);
        var msort=mid.attr('sort');//当前排序
        var ma=mid.parent().find('a');//当前a 标签
        var s=$("img[sort='0']");//主图 图片
        var sid=s.attr('id');
        if(msort!='0')
        {
            //更改
            s.attr('sort',msort);
            s.parent().find('a').html('设置主图').attr("href","javascript:setMainImg('"+sid+"')");
            s.parent().find('.desc').css("display","none");
            //设置主图
            ma.html('主图图片').attr("href","#");//设置主图
            mid.attr('sort','0');//设置主图序号
            mid.parent().find('.desc').css("display","block");

            //修改绑定对象排序
            var oldimglist=$("#imgList").val();
            if(oldimglist!="")
            {
                var oldList=JSON.parse(oldimglist);
                if(oldList!=null&&oldList.length>0)
                {
                    $('#content li').each(function(i){
                        var vid= $(this).find('img').attr('id');
                        if(vid==sid)
                        {
                            oldList[i].sort=msort;
                        }
                        if(vid==id)
                        {
                             oldList[i].sort=0;
                        }
                    });
                }
                var ttt = JSON.stringify(oldList);
                $("#imgList").val(ttt);
            }
        }
    }
    function funover(obj)
    {
        var mid=$(obj).find('img').attr('id'); //当前id
        var msort=$(obj).find('img').attr('sort');//当前排序
        if(msort=="0")
        {
            $(obj).find('a').html('主图图片').attr("href","#");
        }else
        {
             $(obj).find('.desc').css("display","block");
        }
    }
    function funout(obj)
    {
       var mid=$(obj).find('img').attr('id'); //当前id
       var msort=$(obj).find('img').attr('sort');//当前排序
       if(msort!="0")
        {
            $(obj).find('.desc').css("display","none");
        }
    }
    </script>

效果图:

图1:


图2:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值