0

我将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 轴的当前/旧值,并且不抛出 drop 事件。

如何获得 y 轴的新值?

4

1 回答 1

2

我认为您可以使用“突变观察者”来监听每个 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;}   
});
于 2019-04-04T04:30:57.360 回答