jQuery SlideDown / SlideUp | Часто задаваемые вопросы | Открыто

Мое название ничего не значит, я думаю, но сложно назвать мою проблему.

Итак, я сделал раздел в своем html «faq», и когда кто-то нажимает на вопрос, появляется ответ со слайдом вниз. Если мы нажмем на другой вопрос, то закроем предыдущий (slideUp) и откроем тот, на который вы только что нажали. И когда мы нажимаем на вопрос, цвет меняется с .addClass/removeClass на элементе.

Проблема, с которой я борюсь, следующая: когда мы загружаем страницу, я хотел бы, чтобы элемент уже был открыт и только один. Когда мы нажимаем на другую, она закрывает предыдущую и так далее.

Некоторый код будет говорить немного лучше, есть CodePen link. Я хотел бы, чтобы второй элемент уже был открыт :)

Спасибо !


person MaxBresil    schedule 06.03.2018    source источник
comment
Что вы пробовали? Пожалуйста, покажите нам свои усилия   -  person Ionut    schedule 06.03.2018
comment
Я поместил последнюю попытку между комментариями к коду jQuery.   -  person MaxBresil    schedule 06.03.2018
comment
@MaxBresil, пожалуйста, включите всю соответствующую информацию в вопрос   -  person Phydeaux    schedule 06.03.2018


Ответы (2)


Во-первых, вы вызываете функцию slideDown() для элемента с готовым классом open в DOM. Затем вы вызываете метод slideUp для элемента с классом open и удаляете класс open по щелчку. Это должно помочь:

$(function() {
  var $_openedFaq = null;
  
  //calling the slideDown to show the second element in the tabs
  $('a.open').next('p').slideDown();

  function openFaq($__p) {
    $__p.slideDown();
  }


  function closeFaq($__p) {
    $__p.slideUp();
  }

  $('.faq ul li').each(function() {

    var $faq = $(this);
    var $p = $(this).find('p');
    var offset = $(this).offset().top;


    $(this).find('a').click(function(e) {
      e.preventDefault();
      //on click hide the current active elements and remove the class from current active element
      $('a.open').next('p').slideUp();
      $('a.open').removeClass('open');

      $('html, body').animate({
        scrollTop: offset
      }, 500);

      // Test of code that i'm struggling with

      if ($('.faq ul li').find('a').hasClass("open")) {
        $p = $(this).next('p');
        openFaq($p);
      }

      // End of the test

      if ($_openedFaq != null) {
        closeFaq($_openedFaq.find('p'));

        $_openedFaq.find('a').removeClass("open");
      }


      if (($_openedFaq == null) || (($_openedFaq != null) && !$faq.is($_openedFaq))) {
        openFaq($p);

        $_openedFaq = $faq;

        $p.prev('a').addClass("open");

      } else {
        $_openedFaq = null;
      }
    });
  });
});
@font-face {
  font-family: 'Conv_Besom';
  src: url('../font/Besom.eot');
  src: local('☺'), url('../font/Besom.woff') format('woff'), url('../font/Besom.ttf') format('truetype'), url('../font/Besom.svg') format('svg');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: 'Roboto', sans-serif;
  letter-spacing: 1px;
  font-size: 14px;
  font-weight: 500;
}

section {
  background-color: #f9b40a;
}

.faq {
  background-color: #f5f5f5;
  padding-top: 65px;
  padding-bottom: 65px;
}

.faq div.container div.row div.col-sm-6 h1 {
  font-family: 'Source Serif Pro', serif;
  text-align: center;
  font-size: 60px;
  margin: 0;
  padding-bottom: 40px;
}

.faq div.container div.row div.col-sm-6 ul {
  list-style-type: none;
  padding: 0;
}

.faq div.container div.row div.col-sm-6 ul li {
  font-weight: bold;
  font-size: 14px;
  padding: 10px 10px;
  padding-top: 20px;
  border-bottom: 1px solid #bfbfbf;
  position: relative;
}

.faq div.container div.row div.col-sm-6 ul li:last-child {
  border-bottom: none;
}

.faq div.container div.row div.col-sm-6 ul li a {
  text-decoration: none;
  color: #4a4a4a;
  padding-right: auto;
  -webkit-transition: color 0.25s linear;
  -o-transition: color 0.25s linear;
  transition: color 0.25s linear;
}

.faq div.container div.row div.col-sm-6 ul li a:hover {
  color: black;
}

.faq div.container div.row div.col-sm-6 ul li a:hover::after {
  color: black;
}

.faq div.container div.row div.col-sm-6 ul li a::after {
  content: "\f067";
  font-family: 'FontAwesome';
  color: #f9b40a;
  position: absolute;
  top: 20px;
  right: 0;
  -webkit-transition: color 0.25s linear;
  -o-transition: color 0.25s linear;
  transition: color 0.25s linear;
}

.faq div.container div.row div.col-sm-6 ul li a.open {
  color: black;
}

.faq div.container div.row div.col-sm-6 ul li a.open::after {
  content: "\f068";
  font-family: 'FontAwesome';
  ;
  color: black;
  position: absolute;
  top: 20px;
  right: 0;
}

.faq div.container div.row div.col-sm-6 ul li p {
  font-weight: normal;
  display: none;
}

.faq div.container div.row div.col-sm-6 img {
  display: block;
  width: 100%;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Source+Serif+Pro" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="../includes/css/font-awesome.css">
<link href="https://use.fontawesome.com/releases/v5.0.8/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="faq">
  <div class="container">
    <div class="row">
      <div class="col-sm-6">
        <h1>FAQs</h1>
        <ul>
          <li>
            <a href="#">Question 1</a>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </li>
          <li>
            <a class="open" href="#">Question 2</a>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </li>
          <li>
            <a href="#">Question 3</a>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </li>
          <li>
            <a href="#">Question 4</a>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
            </p>
          </li>
        </ul>
      </div>
      <div class="col-sm-6">
        <img src="https://media.forgecdn.net/avatars/107/154/636364134932167010.jpeg" alt="Are you ready ?">
      </div>
    </div>
  </div>
</section>

person Ionut    schedule 06.03.2018
comment
Спасибо за пояснение, я понял :D - person MaxBresil; 06.03.2018

Вы можете просто добавить $('.faq ul li a:first').click(); после загрузки страницы. Это зарегистрирует первый FAQ как открытый. Я бы хотел, чтобы это было последнее заявление вашего $(function(){ ... } звонка

person Napoli    schedule 06.03.2018