如何使用div作为下拉菜单

时间:2018-12-06 13:56:34

标签: jquery html css

假设我有一个这样的代码,并且希望它像下拉菜单一样工作

类似:

ABCD

ABCD
  1234

ABCD
  1234
    abcd

<ul class="first">
  <li class="first-a"><a href="https://someurl">ABCD</a>
    <ul class="second">
      <li class="second-a"><a href="https://someurl">1234</a>
        <ul class="third">
          <li class="third-a"><a href="https://someurl">abcd</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

我用css这样的东西

.first li {
  display:inline-block;
  position: relative;
}

.second {
 display:none;
 position: absolute;
}
.second.open {
  display: block;
}

和这样的js

$( ".first-a" ).click(function() {
  $(".second").removeClass( "open" );
  $(".second", this).toggleClass( "open" );
});
$(window).click(function() {
 $(".second" ).removeClass( "open" );
});
$(".first-a").click(function(event){
    event.stopPropagation();
});

到目前为止,这些方法都没有起作用

1 个答案:

答案 0 :(得分:0)

您可以将一次单击绑定到li(可能想给它一个类,以便它不适用于您项目中的每个li),然后可以使用jquery从每个同级li中删除打开的类,然后切换被点击的类别。

$("li").click(function(e) {
  e.preventDefault();        // prevents the link click firing otherwise you just redirect to the link and no animation will happen
  e.stopPropagation();       // prevents child clicks bubbling up to parent+
  var $thisLi = $(this);     // get the current li that was clicked as a jquery object
  $thisLi.parent().children('li').not($thisLi).removeClass( "open"); // remove class from all sibling lis but not clicked
  $thisLi.toggleClass( "open");                                      // toggle the class on the clicked
});
li {
  position: relative;
}

li>ul {
  display:none;  /* start sub menus hidden */
}

li.open>ul {
  display:block;  /* show sub menu when open class is added to parent li */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="first">
  <li class="first-a"><a href="https://someurl">ABCD</a>
    <ul class="second">
      <li class="second-a"><a href="https://someurl">1234</a>
        <ul class="third">
          <li class="third-a"><a href="https://someurl">abcd</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li class="first-a"><a href="https://someurl">ABCD</a>
    <ul class="second">
      <li class="second-a"><a href="https://someurl">1234</a>
        <ul class="third">
          <li class="third-a"><a href="https://someurl">abcd</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>