sortable.js onChoose 选中事件

sortable.js onChoose 选中事件,当用户点击要拖拽的对象后会回调该事件,该事件会返回一个对象,该对象包含选中的索引,你就可以利用该索引获取你要的数据了。

onChoose事件

属性名称类型说明
onChoosefunction指定选中对象执行的方法
//选中回调函数,evt为参数,要查看evt对象属性请在谷歌浏览器按F12,然后再控制台(console选项卡)查看
 onChoose: function (evt) {  
       console.log(evt);
       var index=evt.oldIndex;  
       document.getElementById("msg").innerHTML ="你选中了第"+index+"个元素"
  }

代码例子

evt返回参数对象结构

完整代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>sortable.js onChoose事件例子</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, minimal-ui">
    <script src="https://www.itxst.com/package/sortable/sortable.min.js"></script>
    <style>
        .box {
        }
        .itxst {
            margin: 10px auto;
            width: 80%;
            float: left;
            margin-right: 10px;
        }

           .itxst > div {
                padding: 6px;
                background-color: #fdfdfd;
                border: solid 1px #eee;
                margin-bottom: 10px;
                cursor: move;
            }


            .itxst .innner {
                padding: 6px;
                background-color: #fdfdfd;
                border: solid 1px #eee;
                margin-bottom: 10px;
                cursor: move;
            }
        #msg {
            clear: both;
            width: 100%;
        }
        .ghost {
            background-color: red !important;
        }
        .chosen {
            border: solid 2px #3089dc !important;
        }
    </style>
</head>
<body>
    <div class="box">
        <div id="g1" class="itxst">
            <div class="item" data-id="item1">item 1</div>
            <div class="item" data-id="item2">item 2</div>
            <div class="item" data-id="item3">item 3</div>
        </div>
    </div>
    <div id="msg"></div>
    <script>
        //第一组
        var g1 = document.getElementById('g1');
        var ops1 = {
            animation: 1000,
            delay: 1,
            draggable: ".item",
            //停靠位置样式
            ghostClass: "ghost",
            //选中样式
            chosenClass: 'chosen',
            //禁用html5原生拖拽行为
            forceFallback: true,
            group: { name: "itxst.com", pull: true, put: true },
            //*********** 选中后执行的方法 ***********
            onChoose: function (evt) {
                console.log(evt);
                var index = evt.oldIndex;
                document.getElementById("msg").innerHTML = "你选中了第" + arr[index] + "元素"
            },
            //拖动结束
            onEnd: function (evt) {


                //获取拖动后的排序
                var arr = sortable1.toArray();
                document.getElementById("msg").innerHTML = "A组排序结果:" + JSON.stringify(arr);
            },
        };
        var sortable1 = Sortable.create(g1, ops1);
        //获取数组
        var arr = sortable1.toArray();


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