如何在resize事件上重新初始化HammerJS?

时间:2016-01-12 22:36:41

标签: javascript jquery resize hammer.js

如何在调整大小事件时重新初始化HammerJS?

我的问题是,当我触发调整大小事件时,选择器重置,并使用jQuery匹配容器$(' .container')将一直返回索引..在文档准备好它以前工作过。

$(' .container')不止一次出现,所以它应该在滑动事件上递增。

有人有任何想法吗?

$(document).ready(function() {
    mobileCalculus(animation);
    swipeActions( $('.home-element-wrapper'), $('.home').width());

    $(window).on('resize', function() {
        mobileCalculus(animation);
    });
});


function swipeActions(parent, offset) {
    var curInd = 0;
    var theThumb = $('.thumb');
    var myElement = document.getElementById('main-swipe');
    var max = theThumb.length - 1;

    // create a simple instance
    // by default, it only adds horizontal recognizers
    var mc = new Hammer(myElement);

    // listen to events...
    mc.on("swipeleft", function(ev) {

        curInd = $('.thumb.active').index() + 1;
        if (curInd > max) {
            curInd = max;
        }
        var newML = offset * curInd;
        theThumb.removeClass('active');
        theThumb.eq(curInd).addClass('active');
        console.log($('.thumb.active').index() + 1);
        parent.css({
            'margin-left': '-'+newML+'px'
        });
    });
    mc.on("swiperight", function(ev) {
        curInd = $('.thumb.active').index() - 1;
        if (curInd < 0) {
            curInd = 0;
        }
        var newML = offset * curInd;
        theThumb.removeClass('active');
        theThumb.eq(curInd).addClass('active');
        parent.css({
            'margin-left': '-'+newML+'px'
        });
    });

}

例如,jquery有一个名为.off的函数,它会停用事件,之后我们可以在选择器上放置一个新事件。

$('element').off('swiperight').on('swiperight')

1 个答案:

答案 0 :(得分:0)

显然我已经明白了。我不得不将var mc = new Hammer(myElement);值设为“全局”。显然,当我在swipeActions()中第二次重新初始化它时,off()函数将无效,因此仅将值初始化一次,然后使用off()on()执行此操作工作

相关问题