简体   繁体   English

单击打开手风琴,单击第二次关闭手风琴

[英]Open accordion on click, close accordion on second click

I've made an accordion element from scratch with help from a tutorial (this is one of my first forays into jQuery), and the behavior I'd like is for accordion elements to open upon clicking, then, if open, close when clicked again. 我已经在教程的帮助下从零开始制作了一个手风琴元素(这是我第一次尝试使用jQuery),我想要的行为是单击时打开手风琴元素,如果打开,则单击时关闭再次。 Here's what I've got: 这是我得到的:

jQuery jQuery的

(function($) {

  var allPanels = $('.accordion > dd').hide();

  $('.accordion > dt > a').click(function() {
    allPanels.slideUp(300);
    $(this).parent().next().slideDown(300)
    return false
  });

})(jQuery);

HTML 的HTML

<dl class="accordion">
<dt><a href="">Question</a></dt>
<dd>Answer</dd>
<dl>

CSS 的CSS

.accordion {  
   dt, dd {
      border-bottom: 0; 
      &:last-of-type {
        border-bottom: 1px solid black; 
      }
      a {
        display: block;
        color: black;
        font-weight: bold;
      }
   }
  dd {
     border-top: 0; 
     &:last-of-type {
       border-top: 1px solid white;
       position: relative;
       top: -1px;
     }
  }
}

Also on jsFiddle here: https://jsfiddle.net/j1f341ku/ 同样在jsFiddle上: https ://jsfiddle.net/j1f341ku/

Currently, when you click an already-open element, it closes and re-opens. 当前,当您单击一个已经打开的元素时,它会关闭并重新打开。 How can I make it so when an already-opened element is clicked, it closes and does not reopen? 当已经打开的元素被单击时,如何关闭它而不重新打开呢? Thanks in advance! 提前致谢!

(PS The suggestions I've found on here for similar problems typically provide solutions for accordions that are built differently.) (PS我在这里找到的针对类似问题的建议通常为手风琴的制造方法有所不同。)

(PPS Long-time reader, first-time poster! Be gentle, sorry if I made any mistakes.) (PPS长期阅读者,第一次张贴海报!请保持谦虚,对不起,如果我有任何错误。)

I've updated your Fiddle: 我已经更新了您的小提琴:

try https://jsfiddle.net/j1f341ku/4/ 尝试https://jsfiddle.net/j1f341ku/4/

(function ($) {

    var $allPanels = $('.accordion > dd').hide();

    $('.accordion > dt > a').click(function (e) {
        e.preventDefault();
        $allPanels.slideToggle(300);
    });

})(jQuery);

Here is an updated fiddle that should fix your bug (I added 3 questions in the fiddle as example): https://jsfiddle.net/j1f341ku/5/ 这是一个更新的小提琴,可以修复您的错误(我在小提琴中添加了3个问题作为示例): https : //jsfiddle.net/j1f341ku/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM