【问题标题】:Basic drop-down menu (jQuery)基本下拉菜单 (jQuery)
【发布时间】:2010-01-13 13:42:15
【问题描述】:

我目前正在使用这个:

$(document).ready(function () {
    $('ul#nav > li').hover(function () {
        $('ul:first', this).show();
    },
    function () {
        $('ul:first', this).hide();
    });
    $('ul#nav li li').hover(function () {
        $('ul:first', this).each(function () {
            $(this).css('top', $(this).parent().position().top);
            $(this).css('left', $(this).parent().position().left + $(this).parent().width());
            $(this).show();
        });
    },
    function () {
        $('ul:first', this).hide();
    });
});

..可以进一步改进/压缩吗?

谢谢。

【问题讨论】:

    标签: javascript jquery html menu drop-down-menu


    【解决方案1】:

    您可以将 $(this).parent 存储在变量和链函数中,除了它看起来非常简单(我在一行上编写匿名单行函数)

    $(document).ready(function () {
        $('ul#nav > li').hover(function () { $('ul:first', this).show(); },
                               function () { $('ul:first', this).hide(); }
        );
        $('ul#nav li li').hover(function () {
            $('ul:first', this).each(function () {
                var p = $(this).parent();
                $(this).css('top', p.position().top)
                       .css('left', p.position().left + p.width())
                       .show();
            });},
            function () { $('ul:first', this).hide(); }
        );
    });
    

    【讨论】:

      【解决方案2】:

      我肯定会替换:

      $(this).css('top', $(this).parent().position().top);
      $(this).css('left', $(this).parent().position().left + $(this).parent().width());
      $(this).show();
      

      与:

      var element = $(this);
      var parent = element.parent();
      var position = parent.position();
      element.css('top', position.top);
      element.css('left', position.left + parent.width());
      element.show();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-27
        • 1970-01-01
        相关资源
        最近更新 更多