index.html 2.67 KB
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

    var byId = function (id) { return document.getElementById(id); };
    Sortable.create(byId('cart1'), {
        group:{
            name:"carts",
            pull:"clone"
        },
        delay:100,
        animation: 150,
        forceFallback: false,
        onAdd: function (evt){
            onAdd();
            onAddItem(evt.item,"#cart1");
        },
        onRemove: function (evt){
            onRemove(evt.item,"#cart1");
        }
    });

    Sortable.create(byId('cart2'), {
        group:{
            name:"carts",
            pull:"clone"
        },
        delay:100,
        animation: 150,
        onAdd: function (evt){
            onAdd();
            onAddItem(evt.item,"#cart2");
        },
        onRemove: function (evt){
            onRemove(evt.item,"#cart2");
        }
    });

    //增加
    function onAddItem(item,form) {
        console.log("onAddItem",form);
        var id=$(item).attr("data-id");
        var itemNumber=Number($(item).find(".cart-number").text());

        var cartList=[];
        $(form).find(".item").map(function (index) {

            var $this=$(this);
            if($this.attr("data-id")==id){
                //最多两个
                var number=Number($this.find(".cart-number").text());
                cartList.push({item:$this,number:number});
            }
        });
        if(cartList.length==1){
            cartList[0].item.find(".cart-number").text("1");
        }else {
            if(cartList[0].number==cartList[1].number){
                //加入的和原来的数量相等
                cartList[0].item.find(".cart-number").text(cartList[0].number+1);
                cartList[1].item.remove();
            }else {
                for(var i=0;i<cartList.length;i++){
                    if(cartList[i].number==itemNumber){
                        cartList[i].item.remove();
                    }else {
                        cartList[i].item.find(".cart-number").text(cartList[i].number+1);
                    }
                }
            }

        }

    }
    //移除元素
    function onRemove(item,form) {
        console.log("onRemove",form);
        var id=$(item).attr("data-id");
        $(form).find(".item").map(function () {
            var $this=$(this);
            if($this.attr("data-id")==id){
                var number=Number($this.find(".cart-number").text());
                if(number==1){
                    $this.remove();
                }else {
                    $this.find(".cart-number").text(number-1);
                }
            }
        });
    }

</script>
</body>
</html>