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

时间:2019-04-04 02:34:21

标签: javascript gridstack

我将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>

因此,事件的阻力和变化也得到了y轴的当前/旧值,并且不会引发掉落的事件。

如何获取y轴的新值?

1 个答案:

答案 0 :(得分: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;}   
});