【问题标题】:How to write jQuery dropdown menus如何编写 jQuery 下拉菜单
【发布时间】:2016-05-19 12:26:40
【问题描述】:

我的页面上有很多下拉菜单可供使用,我需要一些帮助来了解我需要做些什么才能让事情按照我想要的方式工作。我的第一个菜单名为:产品。产品菜单有 3 个选项:运动、交通和学校。这三个选项中的每一个都有自己的下拉菜单,我希望在有人选择它们时显示在产品菜单旁边。有人告诉我使用休闲代码,但我不知道如何使用它,也找不到任何东西可以很好地向我解释。

    $('#Select').change(function(){
       if ($(this).val() == '1') {
           $('#select').css({'display':'block'});           
       }
    });

我现在想再采取这两个步骤。我的运动菜单有 5 个选项可供选择:棒球、篮球、足球、足球和赛车。我将如何编写此代码以在“运动”菜单旁边显示各个运动菜单?

我想采取的另一个步骤:

我的赛车菜单有 3 个选项:Racing1、Racing2 和 Racing3。当有人选择它们时,我将如何编写代码来显示它们每个人的图片?

请您在写答案时向我解释一下代码,因为我有更多的菜单要做,而且我想了解如何做到这一点,所以我可以用我拥有的每个菜单来做。

非常感谢您的帮助。

【问题讨论】:

  • 你能发布更多代码吗?我们将需要您的 HTML 来准确了解您想要实现的目标

标签: jquery


【解决方案1】:

这可能无法直接回答您的问题,但我认为这是我向您提出建议的责任。

与其重新发明轮子,为什么不使用已经为您构建的东西,它是开源的、免费的并且在不同的浏览器/平台上经过大量测试。

所以我从 Bootstrap 框架开始,如果您已经在使用 bootstrap,那么使用 menu 模块实现菜单非常容易。

如果您想要一个独立的解决方案,有成千上万的 options with CSS3 + jQuery combination

如果您仍想从头开始编写菜单,那么您可能会对this answer 感兴趣。

【讨论】:

    【解决方案2】:

    K 所以假设您的项目中包含jQuery,执行您想要的操作就像这样。

    首先创建您的标记 (HTML):

        <div class="page-container">
    
            <div class="selectors-container">
                <div class="selector" data-select="product">Products</div>
                <div class="selector" data-select="sports">Sports</div>
                <div class="selector" data-select="school">School</div>
            </div>
    
            <div class="select-menus">
                <select id="products"><define options here></select>
                <select id="sports"><define options here></select>
                <select id="school"><define options here></select>
            </div>
        </div>
    

    请注意,选择的id 属性等于根项的data-select 属性。

    现在创建一些 CSS 以在开始时隐藏选择,并按照您指定的格式设置它们:

    .selectors-container {
        float:left; //floats make things stack on eachother horizontally.
    }
    .select-menus select {
        display:none; //elements with display:none are invisible.
        float:left; //floats make things stack on eachother horizontally
    }
    .select-menus select.active {
        display:block; //we want to show a select when it has the class 'active' 
    }
    

    现在编写一些jQuery 以使一切正常运行。

    $(".selector").mouseenter(function(event) {
        event.preventDefault(); //makes sure nothing happens that usually does when this event is triggered (redundant here).
        var selectId = $(this).data('select'); //access the element we're hovering by using the `this` keyword, it accesses the element that is triggering the event.
        $(".select-menus select").removeClass("active"); //hide all selects again
        $("#"+selectId).addClass("active"); //show the select that we're hovering.
    });
    

    现在这应该按照你的意愿去做,我确定我在这里和那里忘记了一些细节,但你应该能够弄清楚这些我确定,谷歌是你的朋友。

    【讨论】:

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