基于滑动事件在jQuery Mobile中更新菜单

时间:2012-03-13 15:59:31

标签: jquery jquery-mobile

我有一个基于点击事件更新的菜单,这非常简单,因为我可以点击实际按钮,但如何通过滑动让菜单对页面更改作出反应?

这是我的工作JSFiddle,允许点击和滑动:http://jsfiddle.net/QFX5x/1/

我开始使用pagebeforeshow和.mobile.path.parseURL作为哈希标记,但它不一致。

        $(document).live("pagebeforeshow", function() {
            var obj = $.mobile.path.parseUrl(window.location.href);
            var newPage = '.' + obj.hash;

            alert(newPage);

            //$(newPage).addClass("active");
            //$(newPage).siblings().removeClass("active");
        });

1 个答案:

答案 0 :(得分:1)

当我想模仿某种类型的事件时,我只使用.trigger()在正确的元素上触发该事件,而不是重写我的代码以在两种不同的情况下运行事件处理程序。由于您的代码适用于click事件,因此您可以根据当前click列表项在正确的链接上触发active事件:

$(function(){

    //cache all of the list-items in the navigation div
    var $nav   = $('#nav').children().children(),

        //also cache the number of list-items found
        totNav = $nav.length;

    //notice the use of `.on()` rather than `.live()` since the latter is depreciated
    $(document).on('swipeleft', '.ui-page', function() {

        //get the next index based on the current list-item with the `active` class
        var next = ($nav.filter('.active').index() + 1);

        //if you're already on the last page then stop the function and do nothing
        if (next === totNav) {
            return;
            //you could use this next line to wrap to the beginning rather than not doing anything
            //next = 0;
        }

        //trigger a `click` event on the link within the list-item at the next index
        $nav.eq(next).children().trigger('click');

    //notice I'm chaining the `.on()` function calls on the `$(document)` selection
    }).on('swiperight', '.ui-page', function() {

        //get the previous index
        var prev = ($nav.filter('.active').index() - 1);

        if (prev === -1) {
            return;
            //you could use this next line to wrap to the beginning rather than not doing anything
            //prev = (totNav - 1);
        }
        $nav.eq(prev).children().trigger('click');
    }).on('click', '#nav a', function(e) {

        //more chaining
        $(this).parent().addClass("active").siblings().removeClass("active");
    });
});​

以下是演示:http://jsfiddle.net/QFX5x/4/