Vanilla Javascript Аккордеонная Функциональность - PullRequest
0 голосов
/ 31 мая 2018

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

Я не хочу использовать библиотеку jquery, я хочу иметь возможность кодировать этот код непосредственно на моем веб-сайте.

Я думаю, что необходимый код javascript прост в концепции, но труднопиши для кого-то вроде меня.Я до сих пор не совсем понимаю, как работают команды, функции и т. Д. JavaScript.

Любая помощь или руководство приветствуются!

Вот мой код:

HTML

    <!DOCTYPE html>
      <html>
      <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="accordion.css">
      </head>
      <body>

         <h3 class="accordion">Basics of Sailing</h3>
          <div class="panel">
           <div class="col col-4 middle">
            <!-- <div class="space"></div> -->
             <h4>Before Choosing a Sailboat</h4>
             <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Car Topping & Trailing</h4>
        <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Safety Equipment</h4>
        <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
      </div>
    </div>
    <h3 class="accordion">Basics of Sailing</h3>
    <div class="panel">
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Before Choosing a Sailboat</h4>
        <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
        </div>
        <div class="col col-4 middle">
          <!-- <div class="space"></div> -->
           <h4>Car Topping & Trailing</h4>
          <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
            </div>
          <div class="col col-4 middle">
           <!-- <div class="space"></div> -->
           <h4>Safety Equipment</h4>
           <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
          </div>
         </div>

       <script src="accordion.js"></script>

      </body>
     </html>

CSS

    .accordion {
        background-color: #2364aa;
        color: #ffffff;
        cursor: pointer;
        padding: 18px;
        border: none;
        text-align: left;
        outline: none;
        font-size: 21px;
        transition: 0.4s;
    }

     .open, .accordion:hover {
        background-color: #205A99;
    }

     .accordion:after {
       content: '\f067';
       font-family: "Font Awesome 5 Free";
       color: #ffffff;
       float: right;
       font-size: 1.25em;
       line-height: 25px;
    }

     .open:after {
       content: "\2212";
    }

     .panel {
       max-height: 0;
       overflow: hidden;
       transition: 0.2s ease-out;
    }

    .panel-body {
       padding: 18px 0;
    }

    @media only screen and (min-width: 960px) {
     .container {
       display: table;
       box-sizing: border-box;
   }
     .row .col {
       margin: 10px 0;
   }
     .col {
       display: table-cell;
   }
     .col.middle {
       vertical-align: middle;
   }
     .col-2 {
       width: 50%;
       padding-right: 72px;
   }
     .col-4 {
       width: 33.33333333333333333%;
       padding-right: 72px;
   }
  }

Javascript

   var acc = document.getElementsByClassName("accordion");
   var i;

     for (i = 0; i < acc.length; i++) {
     acc[i].addEventListener("click", function() {
     this.classList.toggle("active");
     var panel = this.nextElementSibling;
       if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
       } else {
       panel.style.maxHeight = panel.scrollHeight + "px";
       }
    });
   }

Ответы [ 2 ]

0 голосов
/ 31 мая 2018

Я надеюсь, что эта функция поможет вам

function closeAll() {
  var accs = document.querySelectorAll('.accordion');
  for(var i = 0; i < accs.length; i ++) {
    accs[i].classList.remove('active');
    var panel = accs[i].nextElementSibling;
    panel.style.maxHeight = null;
  }
}

Обновление Мы можем пропустить закрывающий элемент, щелкнув по которому, добавив это условие к функции closeAll:

if (accs[i] == tar) {
  continue;
}

Полный код здесь

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function(ev) {
    closeAll(ev.target);
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}

function closeAll(tar) {
  var accs = document.querySelectorAll('.accordion');
  for (var i = 0; i < accs.length; i++) {
    if (accs[i] == tar) {
      continue;
    }
    accs[i].classList.remove('active');
    var panel = accs[i].nextElementSibling;
    panel.style.maxHeight = null;
  }
}
.accordion {
  background-color: #2364aa;
  color: #ffffff;
  cursor: pointer;
  padding: 18px;
  border: none;
  text-align: left;
  outline: none;
  font-size: 21px;
  transition: 0.4s;
}

.open,
.accordion:hover {
  background-color: #205A99;
}

.accordion:after {
  content: '\f067';
  font-family: "Font Awesome 5 Free";
  color: #ffffff;
  float: right;
  font-size: 1.25em;
  line-height: 25px;
}

.open:after {
  content: "\2212";
}

.panel {
  max-height: 0;
  overflow: hidden;
  transition: 0.2s ease-out;
}

.panel-body {
  padding: 18px 0;
}

@media only screen and (min-width: 960px) {
  .container {
    display: table;
    box-sizing: border-box;
  }
  .row .col {
    margin: 10px 0;
  }
  .col {
    display: table-cell;
  }
  .col.middle {
    vertical-align: middle;
  }
  .col-2 {
    width: 50%;
    padding-right: 72px;
  }
  .col-4 {
    width: 33.33333333333333333%;
    padding-right: 72px;
  }
}
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="accordion.css">
</head>

<body>

  <h3 class="accordion">Basics of Sailing</h3>
  <div class="panel">
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Before Choosing a Sailboat</h4>
      <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
    </div>
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Car Topping & Trailing</h4>
      <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
    </div>
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Safety Equipment</h4>
      <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
    </div>
  </div>
  <h3 class="accordion">Basics of Sailing</h3>
  <div class="panel">
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Before Choosing a Sailboat</h4>
      <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
    </div>
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Car Topping & Trailing</h4>
      <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
    </div>
    <div class="col col-4 middle">
      <!-- <div class="space"></div> -->
      <h4>Safety Equipment</h4>
      <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
    </div>
  </div>

  <script src="accordion.js"></script>

</body>

</html>
0 голосов
/ 31 мая 2018

Делегирование события


  1. Обернуть все в элемент блока.

    var main = document.querySelector(`main`)
    
  2. Добавить EventListener к этому «родительскому» элементу

    main.addEventListener('click', ....
    
  3. Теперь, если main или при нажатии любых потомков main будет вызвана функция обратного вызова.Таким образом, у нас есть только один EventListener, который прослушивает событие click от имени каждого .accordion.Мы определяем, какой .accordion был фактически нажат, используя условие if и свойство event.target.

  4. Правило взаимная исключительность применяется к принципам работы аккордеона:

    • Только один комбо .accordion + .panel может иметь класс .active.

    • Всякий раз, когда пришло время измениться (в этом случае e.target (выбранный элемент) был нажат), all .accordion s удалит класс .active(есть ли у них это на самом деле или нет).

    • После того, как нет элемента с классом .active, вы затем даете ему e.target.


Изменения


  • .accordion + .panel.active вместо .accordion.active.

  • .style.maxHeight заменено классом .active:

    .panel.active {
      max-height: 2000px;
      height:auto;
      overflow: hidden;
      transition: 0.2s ease-out;
    }
    

Демо

Подробности прокомментированы в Демо


// Reference the parent of all .accordion
var main = document.querySelector('main');

/* Register main to click events...
|| when main or any of its descendant elements are clicked...
*/
main.addEventListener("click", function(e) {

  /* Collect all .accordion into a NodeList and convert it into
  || an array.
  */
  var acc = Array.from(document.querySelectorAll(".accordion"));
  
  /* Loop thru each .accordion  to remove the .active class
  || from each .panel
  */
  for (let a = 0; a < acc.length; a++) {
    var panel = acc[a].nextElementSibling;
    panel.classList.remove('active');
  }
  /* After nothing has class .active, assign .active to the
  || .panel of the clicked element (e.target)
  */
  if (e.target !== e.currentTarget) {
    var tgt = e.target.nextElementSibling;
    tgt.classList.add("active");
  }
});
.accordion {
  background-color: #2364aa;
  color: #ffffff;
  cursor: pointer;
  padding: 18px;
  border: none;
  text-align: left;
  outline: none;
  font-size: 21px;
  transition: 0.4s;
}

.open,
.accordion:hover {
  background-color: #205A99;
}

.accordion:after {
  content: '\f067';
  font-family: "Font Awesome 5 Free";
  color: #ffffff;
  float: right;
  font-size: 1.25em;
  line-height: 25px;
}

.open:after {
  content: "\2212";
}

.panel {
  max-height: 0;
  overflow: hidden;
  transition: 0.2s ease-out;
}

.panel.active {
  max-height: 2000px;
  height:auto;
  overflow: hidden;
  transition: 0.2s ease-out;
}

@media only screen and (min-width: 960px) {
  .container {
    display: table;
    box-sizing: border-box;
  }
  .row .col {
    margin: 10px 0;
  }
  .col {
    display: table-cell;
  }
  .col.middle {
    vertical-align: middle;
  }
  .col-2 {
    width: 50%;
    padding-right: 72px;
  }
  .col-4 {
    width: 33.33333333333333333%;
    padding-right: 72px;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>
  <main>
    <h3 class="accordion">Basics of Sailing</h3>
    <div class="panel">
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Before Choosing a Sailboat</h4>
        <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Car Topping &amp; Trailing</h4>
        <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Safety Equipment</h4>
        <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
      </div>
    </div>
    <h3 class="accordion">Basics of Sailing</h3>
    <div class="panel">
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Before Choosing a Sailboat</h4>
        <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Car Topping & Trailing</h4>
        <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Safety Equipment</h4>
        <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
      </div>
    </div>
    <h3 class="accordion">Basics of Sailing</h3>
    <div class="panel">
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Before Choosing a Sailboat</h4>
        <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Car Topping & Trailing</h4>
        <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Safety Equipment</h4>
        <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
      </div>
    </div>
    <h3 class="accordion">Basics of Sailing</h3>
    <div class="panel">
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Before Choosing a Sailboat</h4>
        <p>Before looking for a boat to buy, you need to first know what you want to do with the boat, whether that is to go on vacation, learn how to sail, competitions or recreational sailing.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Car Topping & Trailing</h4>
        <p>It's a good practice to carry the boat upside-down to allow the sides to rest on the side of the roof racks and to prevent the hull from getting damaged.</p>
      </div>
      <div class="col col-4 middle">
        <!-- <div class="space"></div> -->
        <h4>Safety Equipment</h4>
        <p>You have to always have to think: safety first. Sailing is a dangerous and could result in severe injuries or death if the proper precautions are not taken.</p>
      </div>
    </div>
  </main>

</body>

</html>
...