JQuery меню - PullRequest
       21

JQuery меню

0 голосов
/ 18 июля 2009

Я использую этот скрипт меню jQuery:

(function($) {
    $.fn.blowfish = function() {

    // hide original ul dom tree
    $(this).hide();

    // create container from top-level li tags
    var top = $(this).children('li');
    var container = $('<div/>').addClass('bfcontainer').attr('id', 'cv' + Math.floor(Math.random()*10e10)).insertAfter(this);
    var topdiv = $('<div class="top"></div>').appendTo(container);

    // check if IE and set fixed width for first column
    if($.browser.msie) {
        $('.top').width('200px');
    }

    $.each(top, function(i, item) {
        var topitem = $(':eq(0)', item).clone().data('sub', $(item).children('ul')).appendTo(topdiv);

        if($(topitem).data('sub').length) {
            $(topitem).addClass('hasChildMenu');

            if($.browser.safari) {
                $(topitem).css({'margin-right' : '15px'});
            }
        }
    });

    // event handlers
    $('a', container).live('click', function() {
        var container = $(this).parents('.bfcontainer');

        // click handler
        var level = $('div', container).index($(this).parents('div'));

        // remove blocks to the right in the tree, and 'deactivate' other links within the same level
        $('div:gt('+level+')', container).remove();
        $('div:eq('+level+') a', container).removeClass('active').removeClass('inpath');
        $('.active', container).addClass('inpath');
        $(this).addClass('active');

        if($(this).data('sub').children('li').length) {
            // add submenu if container has children
            submenu(container, this);
        }
        else {
            // show title or link if container has no children
            var title = $('<a/>').attr({href : $(this).attr('href')}).text($(this).attr('title') ? $(this).attr('title') : $(this).text());
            var featurebox = $('<div/>').html(title).addClass('feature').appendTo(container);

            // set width
            var remainingspace = 0;

            $.each($(container).children('div').slice(0, -1), function(i, item) {
                remainingspace += $(item).width();
            });

            var fillwidth = $(container).width() - remainingspace;

            $(featurebox).css({'top': 0, 'left' : remainingspace}).width(fillwidth).show('slow');
        }

        return false;
    });
};

// create submenus
function submenu(container, item) {
    var leftPos = 0;

    $.each($(container).children('div'), function(i, mydiv) {
        leftPos += $(mydiv).width();
    });

    var submenu = $('<div/>').css({'top' : 0, 'left' : leftPos}).appendTo(container).fadeIn();

    // check if IE and set fixed width for submenu column
    if($.browser.msie) {
        $(submenu).width('200px');
    }

    var subitems = $(item).data('sub').children('li');

    $.each(subitems, function(i, subitem) {
        var subsubitem = $(':eq(0)', subitem).clone().data('sub', $(subitem).children('ul')).appendTo(submenu);

        if($(subsubitem).data('sub').length) {
            $(subsubitem).addClass('hasChildMenu');

            if($.browser.safari) {
                $(subsubitem).css({'margin-right' : '15px' });
            }
        }
    });
}  
})(jQuery);

Исходное дерево DOM выглядит так:

<ul>
    <li>
        <a href="#">Item</a>

        <ul>
            <li>
                <a href="#">Item 2</a>
            </li>

            <li>
                <a href="#">Item 2</a>

                <ul>
                    <li>
                        <a href="#">Item 3</a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>

    <li>
        <a href="#">Item 4</a>
    </li>
</ul>

Скрипты jQuery добавляют новый столбец для каждого подменю (например, искатель Mac OS X), и я хочу изменить его, чтобы, если больше нет подменю, он фактически получал атрибут href ссылки и вел себя как обычный (Я использую AJAX для загрузки содержимого в другой div, если вы щелкаете по элементу без подэлементов, поэтому я не могу использовать window.location в самом скрипте, а вместо этого должен отключить возврат false в этом конкретном случае.

Рабочий пример можно посмотреть здесь: http://mxms.me/blowfish

Большое спасибо.

1 Ответ

1 голос
/ 18 июля 2009

Хорошо, собираюсь ответить на мой собственный вопрос: D!

Вот обновление JS:

(function($) {
    $.fn.blowfish = function() {

    // hide original ul dom tree
    $(this).hide();

    // create container from top-level li tags
    var top = $(this).children('li');
    var container = $('<div/>').addClass('bfcontainer').attr('id', 'cv' + Math.floor(Math.random()*10e10)).insertAfter(this);
    var topdiv = $('<div class="top"></div>').appendTo(container);

    // check if IE and set fixed width for first column
    if($.browser.msie) {
        $('.top').width('200px');
    }

    $.each(top, function(i, item) {
        var topitem = $(':eq(0)', item).clone().data('sub', $(item).children('ul')).appendTo(topdiv);

        if($(topitem).data('sub').length) {
            $(topitem).addClass('hasChildMenu');

            if($.browser.safari) {
                $(topitem).css({'margin-right' : '15px'});
            }
        }
    });

    // event handlers
    $('a', container).live('click', function() {
        var container = $(this).parents('.bfcontainer');

        // click handler
        var level = $('div', container).index($(this).parents('div'));

        // remove blocks to the right in the tree, and 'deactivate' other links within the same level
        $('div:gt('+level+')', container).remove();
        $('div:eq('+level+') a', container).removeClass('active').removeClass('inpath');
        $('.active', container).addClass('inpath');
        $(this).addClass('active');

        if($(this).data('sub').children('li').length) {
            // add submenu if container has children
            submenu(container, this);

            return false;
        }
        else {
            // show title or link if container has no children
            /*
var title = $('<a/>').attr({href : $(this).attr('href')}).text($(this).attr('title') ? $(this).attr('title') : $(this).text());
            var featurebox = $('<div/>').html(title).addClass('feature').appendTo(container);

            // set width
            var remainingspace = 0;

            $.each($(container).children('div').slice(0, -1), function(i, item) {
                remainingspace += $(item).width();
            });

            var fillwidth = $(container).width() - remainingspace;

            $(featurebox).css({'top': 0, 'left' : remainingspace}).width(fillwidth).show('slow');
*/
            /* window.location($(this).attr('href')); */
        }
    });
};

// create submenus
function submenu(container, item) {
    var leftPos = 0;

    $.each($(container).children('div'), function(i, mydiv) {
        leftPos += $(mydiv).width();
    });

    var submenu = $('<div/>').css({'top' : 0, 'left' : leftPos}).appendTo(container).fadeIn();

    // check if IE and set fixed width for submenu column
    if($.browser.msie) {
        $(submenu).width('200px');
    }

    var subitems = $(item).data('sub').children('li');

    $.each(subitems, function(i, subitem) {
        var subsubitem = $(':eq(0)', subitem).clone().data('sub', $(subitem).children('ul')).appendTo(submenu);

        if($(subsubitem).data('sub').length) {
            $(subsubitem).addClass('hasChildMenu');

            if($.browser.safari) {
                $(subsubitem).css({'margin-right' : '15px' });
            }
        }
    });
}  
})(jQuery);

Cheers, Max

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...