0

我正在使用 Packery JS 创建卡片布局。在这个布局中,我使用fit 方法移动东西。移动完成后,我滚动到移动的 div;我等待fit 完成事件,然后使用 jQuery 的 scrolltop 滚动到有问题的 div。这是我目前用于滚动部分的代码:

$container.packery( 'on', 'fitComplete', function () {
    $('html,body').animate({
        scrollTop: $("#" + moveItem).offset().top - 40
    });
    console.log("scroll to: " + moveItem + ", position: " +($("#"+moveItem).offset().top - 40))
});

在第一次单击时,它按预期工作,这是移动 div#vision 的输出:

scroll to: vision, position: 69

但在第二次点击(移动 div#project-6)时出错了:

scroll to: project-6, position: 616
scroll to: vision, position: 69

它首先滚动到 project-6,然后立即转到 moveItem 的前一个值 vision。在随后的点击中,列表只会变长。

所以我的问题是:为什么要记住 moveItem 变量的先前值?我怎样才能阻止它这样做?

就上下文而言,这是我正在使用它的网站。有问题的代码可以通过搜索“//Move function”找到。

提前致谢!

4

2 回答 2

2

当您执行$container.packery( 'on', ...);多次时会发生这种情况。我的猜测是每次单击按钮时都附加另一个事件处理程序,而不是在页面设置中附加一次,然后确保在单击按钮时触发事件。

于 2015-04-17T14:12:40.763 回答
2

我会更具体。将此函数更改为:

                //Move Function
            var moveThis = function(moveItem, moveTarget){
                if (moveTarget == "stamp" && $("#" + moveItem).hasClass("w2") && 720 < window.innerWidth && window.innerWidth < 992) {
                    var targetX = 0;
                    var targetY = $("#stamp").height() + 40;
                    $container.packery('fit', document.getElementById(moveItem), targetX, targetY);
                } else if (moveTarget == "stamp") {
                    var arrayList = $container.packery('getItemElements')
                    var targetX = $(arrayList[0]).position().left
                    var targetY = $(arrayList[0]).position().top
                    $container.packery('fit', document.getElementById(moveItem), targetX, targetY);
                } else {
                    var arrayList = $container.packery('getItemElements')
                    positionList = arrayList.indexOf(document.getElementById(moveTarget))
                    var targetX = $(arrayList[positionList+1]).position().left
                    var targetY = $(arrayList[positionList+1]).position().top
                    $container.packery('fit', document.getElementById(moveItem), targetX, targetY);
                }

            };

此代码必须在全局定义的某个地方失效:

 $container.packery( 'on', 'fitComplete', function ( moveItem ) {
                    $('html,body').animate({
                        scrollTop: $("#" + $(moveItem.element).attr('id')).offset().top - 40
                    });
                    console.log("scroll to: " + $(moveItem.element).attr('id') + ", position: " +($("#"+moveItem).offset().top - 40))
                });

我不确定$(moveItem.element).attr('id')-看看控制台它有什么

于 2015-04-17T14:26:47.450 回答