如何在 gridstack.js 内获取新的 y 值

How to get the new y-value within gridstack.js

我将 Gridstack 用于可拖动的 div。 我如何获得 data-gs-y 的新值(所以 div 被丢弃到哪个 y 轴)。 其实我试过这个:

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="grid-stack" data-gs-width="12" data-gs-animate="yes">
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="0" data-gs-width="12" data-gs-height="1" data-gs-id="facebook">
                        <div class="grid-stack-item-content">facebook</div>
                    </div>
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="1" data-gs-width="12" data-gs-height="1" data-gs-id="workbook">
                        <div class="grid-stack-item-content">workbook</div>
                    </div>
                    <div class="grid-stack-item" data-gs-x="0" data-gs-y="2" data-gs-width="12" data-gs-height="1" data-gs-id="pictures">
                        <div class="grid-stack-item-content">pictures</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        $('.grid-stack').gridstack({
            disableResize: true,
            removable: true
        });
    });

    $('.grid-stack').on('dragstop', function(event, ui) {
            var element = event.target;
            var id = $(element).attr('data-gs-id');
            var y = $(element).attr('data-gs-y');
            alert(id + y);
        });

    $('.grid-stack').on('dropped', function (event, previousWidget, newWidget) {
        alert('dropped'); // It's not thrown
    });

    $('.grid-stack').on('change', function(event, items) {
        var element = items[0].el[0];
        var id = $(element).attr('data-gs-id');
        var y = $(element).attr('data-gs-y');
        alert(id + y);
    });
</script>

所以事件 dragstop 和 change 给了我 y 轴的 current/old 值并且没有抛出 dropped 事件..

如何获取 y 轴的新值?

我认为您可以使用 "mutation observer" 来监听每个 div 元素上属性 'data-gs-y' 的变化。我写了下面的代码并验证了这个演示 http://gridstackjs.com/demo/knockout.html

var divs = document.querySelectorAll(".grid-stack-item");
var dragging = false;
divs.forEach(function(div){
 const observer = new MutationObserver((mutations) => { 
   mutations.forEach((mutation) => {
     if(!dragging){
       alert("new y-value " + div.getAttribute("data-gs-y"));
     }
   });
 });
observer.observe(div, { attributes: true, attributeFilter: ['data-gs-y'] });

div.onmousedown = function(){ dragging = true;}
div.onmouseup = function(){ dragging = false;}   
});