Как плавно открыть аккордеон?
Есть такой аккордеон:
<!-- wp:details {"summary":"Детали:"} --> <details class="wp-block-details"> <summary>Детали:</summary><!-- wp:list {"fontSize":"small"} --> <ul class="has-small-font-size"> <!-- wp:list-item --> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <!-- /wp:list-item --> |
<!-- wp:details {"summary":"Детали:"} --> <details class="wp-block-details"> <summary>Детали:</summary><!-- wp:list {"fontSize":"small"} --> <ul class="has-small-font-size"> <!-- wp:list-item --> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <li>Пример текста</li> <!-- /wp:list-item -->
JS + jQuery:
var animationTime = 2000; $(".wp-block-details > summary").click(function() { $(this).next().stop(true, true).slideToggle(animationTime); }); |
var animationTime = 2000; $(".wp-block-details > summary").click(function() { $(this).next().stop(true, true).slideToggle(animationTime); });
в данном случае почему-то быстро открывается и плавно закрывается.
Дополнительно:
Решение найдено здесь
<!DOCTYPE html> <html> <head> <title>Example of smooth opening of an accordion using jQuery</title> <style> body { background-color: #1b1b1b; color: #ccc; } </style> </head> <body> <details> <summary>Details:</summary> <ul> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> </ul> </details> <script src="https://code.jquery.com/jquery-3.7.1.js"></script> <script> $('details summary').each(function() { var animationTime = 1000; var $Wrapper = $(this).nextAll().wrapAll('<div></div>').parent(); // Hide elements that are not open by default if(!$(this).parent('details').attr('open')) $Wrapper.hide(); $(this).click(function(Event) { Event.preventDefault(); if($(this).parent('details').attr('open')) { $Wrapper.slideUp(animationTime, function() { // Remove the open attribute after sliding so, so the animation is visible in browsers supporting the <details> element $(this).parent('details').removeAttr('open'); }); } else { // Add the open attribute before sliding down, so the animation is visible in browsers supporting the <details> element $(this).parent('details').attr('open', true); $Wrapper.slideDown(animationTime); } }); }); </script> </body> </html> |
<!DOCTYPE html> <html> <head> <title>Example of smooth opening of an accordion using jQuery</title> <style> body { background-color: #1b1b1b; color: #ccc; } </style> </head> <body> <details> <summary>Details:</summary> <ul> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> <li>Content</li> </ul> </details> <script src="https://code.jquery.com/jquery-3.7.1.js"></script> <script> $('details summary').each(function() { var animationTime = 1000; var $Wrapper = $(this).nextAll().wrapAll('<div></div>').parent(); // Hide elements that are not open by default if(!$(this).parent('details').attr('open')) $Wrapper.hide(); $(this).click(function(Event) { Event.preventDefault(); if($(this).parent('details').attr('open')) { $Wrapper.slideUp(animationTime, function() { // Remove the open attribute after sliding so, so the animation is visible in browsers supporting the <details> element $(this).parent('details').removeAttr('open'); }); } else { // Add the open attribute before sliding down, so the animation is visible in browsers supporting the <details> element $(this).parent('details').attr('open', true); $Wrapper.slideDown(animationTime); } }); }); </script> </body> </html>
Ответы:
const details = document.querySelector('details') details.addEventListener('click', (e)=> { e.preventDefault() //....rest code }) |
const details = document.querySelector('details') details.addEventListener('click', (e)=> { e.preventDefault() //....rest code })
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для плавного открытия аккордеона на веб-странице можно использовать JavaScript и CSS. Вот пример кода, который позволит реализовать данную функциональность:
HTML:
```html
```
CSS:
```css
.accordion-content {
display: none;
overflow: hidden;
transition: height 0.3s;
}
```
JavaScript:
```php
document.addEventListener("DOMContentLoaded", function() {
const accordionItems = document.querySelectorAll(".accordion-item");
accordionItems.forEach(item => {
const heading = item.querySelector(".accordion-heading");
const content = item.querySelector(".accordion-content");
heading.addEventListener("click", function() {
if (content.style.display === "block") {
content.style.display = "none";
content.style.height = "0";
} else {
content.style.display = "block";
content.style.height = content.scrollHeight + "px";
}
});
});
});
```
Этот код создает аккордеон с двумя пунктами, которые можно открывать и закрывать, плавно изменяя высоту содержимого. При клике на заголовок аккордеона, скрипт проверяет текущее состояние содержимого и анимирует его открытие или закрытие.
Вы можете расширить этот пример, добавив больше пунктов аккордеона или настраивая стилизацию с помощью CSS. Надеюсь, это поможет вам реализовать плавное открытие аккордеона на вашем веб-сайте.