如何在resize事件上触发我的jQuery脚本

时间:2013-03-13 10:52:03

标签: jquery navigation responsive-design

我有一个jQuery脚本,可以将我的菜单重组为一个select表单元素,它可以正常工作。

我想在.resize()事件中触发它,但我无法让它工作。我怎么做?

 $(function () {
    $(window).resize(function () {
        /* Get the window's width, and check whether it is narrower than 580 pixels */
        var windowWidth = $(window).width();
        if (windowWidth <= 580) {

            /* Clone our navigation */
            var mainNavigation = $('nav.main-navigation').clone();

            /* Replace unordered list with a "select" element to be populated with options, and create a variable to select our new empty option menu */
            $('nav.main-navigation').html('<select class="menu"></select>');
            var selectMenu = $('select.menu');

            /* Navigate our nav clone for information needed to populate options */
            $(mainNavigation).children('ul').children('li').each(function () {

                /* Get top-level link and text */
                var href = $(this).children('a').attr('href');
                var text = $(this).children('a').text();

                /* Append this option to our "select" */
                $(selectMenu).append('<option value="' + href + '">' + text + '</option>');

                /* Check for "children" and navigate for more options if they exist */
                if ($(this).children('ul').length > 0) {
                    $(this).children('ul').children('li').each(function () {

                        /* Get child-level link and text */
                        var href2 = $(this).children('a').attr('href');
                        var text2 = $(this).children('a').text();

                        /* Append this option to our "select" */
                        $(selectMenu).append('<option value="' + href2 + '">--- ' + text2 + '</option>');
                    });
                }
            });

        }

        /* When our select menu is changed, change the window location to match the value of the selected option. */
        $(selectMenu).change(function () {
            location = this.options[this.selectedIndex].value;
        });
    });
});

1 个答案:

答案 0 :(得分:0)

好吧,试试resize!

$("#div").resize(function(e){
   // do something when #div element resize
});