单击减号时如何折叠手风琴

时间:2019-06-29 06:00:29

标签: javascript jquery

单击减号时,我希望关闭此手风琴。当手风琴处于展开状态时,出现负号。 当前,只有在单击另一个h3时,扩展才会关闭。

我尝试删除h3中打开的类,但没有用。另外,如果您可以让动画持续崩溃,那就太好了。

尝试过这没用

$('.accordion > h3').on('click', function() {
    if($(this).hasClass("opened")) {
        $(this).removeClass('opened');
    }

"use strict";

var head, //".accordion > h3"
	content, //".accordion > div"
	animateTime = 500;

//при клике по заголовку...
$(".accordion > h3").click(function () {

	head = $(this);
	content = $(this).next("div");

	//Перебрать элементы массива (все h3)
	$(".accordion > h3").each(function (index) {
		let elem = $(this);

		//Проверить, есть ли уже растрытые блоки. Если есть - закрыть.
		if (elem.attr("class") === "opened") {
			elem.removeClass("opened");
			elem.next("div").stop().animate({
				height: '0'
			}, animateTime);
		}
	});

	//Добавить заголовку раскрываемого блока класс "opened"
	head.addClass("opened");

	//Плавно раскрыть блок с контентом
	autoHeightAnimate(content, animateTime);

	//Прокрутить страницу до раскрытого заголовка
	//это нужно, чтобы контент не уплывал вверх, особенно на маленьких экранах и при большом объеме контента
	setTimeout(function () {
		$("html, body").animate({
			scrollTop: head.offset().top
		}, animateTime);
	}, animateTime);

	/*****/
	/* Функция для - animate height: auto */
	function autoHeightAnimate(element, time) {
		var curHeight = element.height(), // Получить высоту по умолчанию
			autoHeight = element.css('height', 'auto').height(); // Сделать высоту auto

		element.height(curHeight); //Переустановить высоту
		element.stop().animate({
			height: autoHeight
		}, time);
	}

});
.accordion > h3 {
	position: relative;
	font-size: 18px; height:60px; border-radius:8px;
	margin: 0 0 10px 0;
	cursor: pointer;
	line-height: 34px;
	background: #f1f2f3;
	color: #333;
	font-weight: 700;
}
.accordion > h3 div{padding:12px 0 0 70px !important;}
.accordion > h3::before {
	content: '+'; border-radius:8px 0 0 8px;
	display: inline-block;
	position: absolute;
	width: 50px;
	height: 100%;
	left: 0;
	background: orange;
	color: #fff;
	font-weight: bold;
	font-size: 2em;
	text-align: center; padding:12px 0 0 0 !important;
	
}
.accordion p{padding:8px 0 8px 0 !important; margin:0 !important; overflow:auto;}
.accordion > h3.opened {color: #333;}
.accordion > h3.opened::before {content: '-'; line-height: 110%; background: #80cc26;}
.accordion > div {height: 0; overflow: hidden;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordion">
              <h3>
                <div>
                  <h3>Vulputate ut pharetra sit amet aliquam id diam maecenas</h3>
                </div>
              </h3>
                <div>
                  <p></p>
                  <h1>Vulputate</h1>
                  <p></p>
                  <h1>Commodo sed egestas egestas</h1>
                  <ul>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                  </ul>
                  <p></p>
                </div>
              <h3>
                <div>
                  <h3>Blandit aliquam etiam erat velit scelerisque</h3>
                </div>
              </h3>
                <div>
                  <p></p>
                  <h1>Commodo sed</h1
                  <p></p>
                  <h1>Pretium viverra suspendisse potenti</h1>
                  <ul>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                  </ul>
                  <p></p>
                </div>
                <h3>
                <div>
                  <h3>Pretium viverra suspendisse potenti</h3>
                </div>
              </h3>
                <div>
                  <p></p>
                  <h1>Pretium viverra suspendisse 
                  <p></p>
                  <ul>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                    <li>Pretium viverra suspendisse potenti</li>
                  </ul>
                  <p></p>
                </div>
              </div>

2 个答案:

答案 0 :(得分:0)

有一个我认为可以使用的.toogle()方法。您可以找到文档here

答案 1 :(得分:0)

问题是:在您的代码中,您addClass('opened')并运行autoHeightAnimate,每次单击<h3>时它们都会触发,因此您需要一个{{ 1}}语句条件以采取相反的操作

[1] 要检查班级,请使用if而不是.hasClass()

[2] 无需循环访问.attr('class')可以更容易地检查<h3> this hasClass { {1}},然后执行其他操作,然后执行相反的操作..请阅读下面代码中的注释

<h3>
opened
"use strict";

var head, //".accordion > h3"
content, //".accordion > div"
animateTime = 500;

//при клике по заголовку...
$(".accordion > h3").click(function () {

  var head = $(this);
  var content = $(this).next("div");
  var not_head = $(".accordion > h3").not(head);
  var not_content = $(".accordion > h3").not(head).next('div');

  //Проверить, есть ли уже растрытые блоки. Если есть - закрыть.
  if (head.hasClass("opened")) {  // check if this h3 hasclass opened
    $(".accordion > h3").removeClass("opened");   // remove opened class from all h3
    $(".accordion > h3").next("div").stop().animate({  // close all next div
    height: '0'
    }, animateTime);
  }else{
    not_head.removeClass('opened');  // remove opened class from h3 but not the clicked one
    not_content.stop().animate({  // close next div but not the next of the clicked h3
    height: '0'
    }, animateTime);
    head.addClass('opened');   // addclass opened to this h3
    //Плавно раскрыть блок с контентом
    autoHeightAnimate(content, animateTime); // open the next div of this h3
  }


  //Прокрутить страницу до раскрытого заголовка
  //это нужно, чтобы контент не уплывал вверх, особенно на маленьких экранах и при большом объеме контента
  setTimeout(function () {
    $("html, body").animate({
    scrollTop: head.offset().top
    }, animateTime);
  }, animateTime);
});


/*****/
/* Функция для - animate height: auto */
function autoHeightAnimate(element, time) {
  var curHeight = element.height(), // Получить высоту по умолчанию
  autoHeight = element.css('height', 'auto').height(); // Сделать высоту auto

  element.height(curHeight); //Переустановить высоту
  element.stop().animate({
  height: autoHeight
  }, time);
 }

其他:无需在click事件中编写函数。您可以将其拉出click事件,并且仍然可以使用