下拉菜单一次打开一次

时间:2018-10-04 21:01:56

标签: javascript jquery html css

我有一个包含子菜单的ul li列表。默认情况下,子菜单是隐藏的。当我单击第一个li a时,此子菜单将向下滑动。当我单击第二个“ li a”时,第二个子菜单将向下滑动。

一个问题是,当我单击第二个li a时,第一个子菜单将向上滑动。这意味着一次只能打开一个子菜单。

请帮帮我。

jsFiddle

$(document).ready(function () {
    $('li a').on('click', function(){
        $(this).siblings().slideToggle();
    });
});
li {padding:20px; border: solid 1px;margin:5px;}

.square {
  display: none;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>
        <a>Hover List1</a>
        <div class="square">
        Square 1
        </div>
    </li>
    <li>
        <a>Hover List2</a>
        <div class="square">
        Square 2
        </div>
    </li>
    <li>
        <a>Hover List3</a>
        <div class="square">
        Square 3
        </div>
    </li>
    <li>
        <a>Hover List4</a>
        <div class="square">
        Square 4
        </div>
    </li>
</ul>

2 个答案:

答案 0 :(得分:0)

$(document).ready(function () {
    $('li a').on('click', function(){
            $('.square').removeClass('active');
        $(this).siblings().addClass('active');
    });
});
li {padding:20px; border: solid 1px;margin:5px;}

.square {
  display: none;
  border: 1px solid red;
}
.active {
  display: block;
  border: 1px solid red;
}

答案 1 :(得分:0)

您需要一种方法来了解“开放”元素的位置。

$(document).ready(function() {
  $('li a').on('click', function() {
    $this = $(this);
    $opened = $this.closest('ul').find('.open');
    $siblings = $this.siblings();
    if (!$siblings.is($opened)) {
      // toggleClass() will work too, but this is more explicit
      $opened.slideToggle().removeClass('open');
      // This will inhibit the closing of an open element if clicked.
      // Move the previous line before the 'if' if you don't want this behaviour.
      $siblings.slideToggle().addClass('open');
    }
  });
});
li {
  padding: 20px;
  border: solid 1px;
  margin: 5px;
}

.square {
  display: none;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <a>Hover List1</a>
    <div class="square">
      Square 1
    </div>
  </li>
  <li>
    <a>Hover List2</a>
    <div class="square">
      Square 2
    </div>
  </li>
  <li>
    <a>Hover List3</a>
    <div class="square">
      Square 3
    </div>
  </li>
  <li>
    <a>Hover List4</a>
    <div class="square">
      Square 4
    </div>
  </li>
</ul>