#javascript #html
Вопрос:
Я хочу сделать аккордеон, но я не знаю, как ввести стиль «аккордеон__содержимое», который находится внутри «аккордеона», чтобы изменить отображение с блока на нет.
Я хочу сделать аккордеон, но я не знаю, как ввести стиль «аккордеон__содержимое», который находится внутри «аккордеона», чтобы изменить отображение с блока на нет. Я хочу сделать аккордеон, но я не знаю, как ввести стиль «аккордеон__содержимое», который находится внутри «аккордеона», чтобы изменить отображение с блока на нет. Я хочу сделать аккордеон, но я не знаю, как ввести стиль «аккордеон__содержимое», который находится внутри «аккордеона», чтобы изменить отображение с блока на нет.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<link rel="stylesheet" href="style.css">
<title>Frontend Mentor | FAQ Accordion Card</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }
</style>
</head>
<body>
<img class="imgback" src="/design/desktop-design.jpg" alt="">
<div class="container">
<img src="images/illustration-box-desktop.svg" alt="" class="box__svg">
<div class="sub__container">
<img src="images/bg-pattern-desktop.svg" alt="" class="bg__svg">
<img src="images/illustration-woman-online-desktop.svg" alt="" class="women__svg">
<div class="faq">
<h1 class="faq__tittle">FAQ</h1>
<div class="accordion__container">
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">How many team members can I invite?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content">
<p >You can invite up to 2 additional users on the Free plan. There is no limit on
team members for the Premium plan.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">What is the maximum file upload size?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content">
<p>No more than 2GB. All files in your account must fit your allotted storage space.
</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">How do I reset my password?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content">
<p>Click “Forgot password” from the login page or “Change password” from your profile
A reset link will be emailed to you.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">Can I cancel my subscription?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content">
<p>Yes! Send us a message and we’ll process your request no questions asked.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">Do you provide additional support?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content">
<p>Chat and email support is available 24/7. Phone lines are open during normal</p>
</div>
</div>
<hr>
</div>
</div>
</div>
</div>
<script>
var acc = document.getElementsByClassName("accordion");
for (let i = 0; i<acc.length; i ){
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
/* var panel = this.nextElemenSibling;
console.log(panel);
if(panel.style.display === "block"){
panel.style.display = "none";
}
else{
panel.style.display = "block";
} */
});
}
</script>
</body>
</html>
Ответ №1:
Вы ищете this.children[1]
в своем JS, чтобы нацелить ребенка аккордеонов на класс accordion__content
Затем вы можете создать класс, который добавит отображение none к accordion__tittle
элементам, добавляя по умолчанию в HTML. Используйте JS, чтобы переключить его в прослушивателе событий щелчка.
Я не убирал ваш CSS, просто показал вам, как добавлять/удалять, используя условие, которое вы уже написали.
В качестве альтернативы вы можете просто написать условие, чтобы проверить, будет ли el.style.display = block
затем добавлено/удалено, как вы сделали в своем пин-коде.
ПРИМЕЧАНИЕ: Я удалил все остальные html и CSS, чтобы просто сосредоточиться на вашем вопросе.
const acc = document.getElementsByClassName("accordion")
// much cleaner JS
for (let i = 0; i < acc.length; i ) {
acc[i].addEventListener("click", function() {
this.classList.toggle("active")
this.children[1].classList.toggle('display-none') // toggle the class .display-none no conditional needed
})
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
/*ACCORDION*/
/* Added this class to use for toggling display of none to your accordian elements */
.display-none {
display: none;
}
.accordion__container {
padding-top: 20px;
padding-right: 15%;
}
.accordion {
cursor: pointer;
display: flex;
flex-direction: column;
justify-content: center;
height: 3.5rem;
width: 100%;
}
.active .accordion {
background: green;
}
.accordion__tittle {
position: relative;
font-size: 0.9rem;
font-weight: 700;
}
.arrow {
position: absolute;
right: 5%;
top: 50%;
transform: translateY(-50%);
}
.accordion__content {
height: 40px;
width: 90%;
padding-top: 10px;
font-size: 0.8rem;
font-weight: 400;
}
.active {
background-color: seagreen;
}
hr {
opacity: 0.7;
}
.attribution {
position: absolute;
bottom: 0;
}
<div class="accordion__container">
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">How many team members can I invite?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content display-none">
<p>You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">What is the maximum file upload size?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content display-none">
<p>No more than 2GB. All files in your account must fit your allotted storage space.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">How do I reset my password?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content display-none">
<p>Click “Forgot password” from the login page or “Change password” from your profile page. A reset link will be emailed to you.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">Can I cancel my subscription?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content display-none">
<p>Yes! Send us a message and we’ll process your request no questions asked.</p>
</div>
</div>
<hr>
<div class="accordion">
<div class="accordion__tittle">
<h4 class="tittle">Do you provide additional support?</h4>
<img src="./images/icon-arrow-down.svg" alt="" class="arrow">
</div>
<div class="accordion__content display-none">
<p>Chat and email support is available 24/7. Phone lines are open during normal business hours.</p>
</div>
</div>
<hr>
</div>
Комментарии:
1. по какой-то причине в консоли я получил «неопределенный», поэтому я использовал этот.lastElementChild. Я должен практиковаться разными способами, большое вам спасибо.
Ответ №2:
Чтобы выбрать все элементы с одним и тем же классом:
const accordions = document.querySelectorAll('.accordion');
Это список узлов, примерно такой же, как массив, индекс которого начинается с 0.
Если вы хотите выбрать первый аккордеон, то:
const youAccordion = accordions[0];
и так далее.
Комментарии:
1. Я еще не пробовал это решение, мне нужно практиковаться другими способами. большое спасибо.
Ответ №3:
Вы должны получить это свойство.lastElementChild в функции обработчика щелчка, ваша функция будет:
....
acc[i].addEventListener("click", function() {
this.classList.toggle("active");
//var panel = this.nextElementSibling;//
var panel = this.lastElementChild;
console.log(panel);
if(panel.style.display === "block"){
panel.style.display = "none";
}
else{
panel.style.display = "block";
}
});
....
Комментарии:
1. Я нашел это очень полезным, большое вам спасибо.