Сейчас узнаем, какой подарок выпадет именно Вам
Крутите колесо
Как сделать аккордеон с зависимой картинкой в ZeroBlock Tilda
Eva Stark
Eva is the voice of our brand. She spends hours making our clients feel cared for and enjoying their communication with the company. If you have any suggestions or ideas, you can write to her.
Julia Bush
Julia takes care of everything you can see. She spent five years in London learning visual communication. She uses her knowledge to make the world a little more beautiful.
Max Holden
Max founded our company. He is the father of our main goals and values. He found the core members of our team and helped them to show their unique talents in the work process.
Emily Carter
Emily Carter is a dedicated and supportive tutor who prepares students in various school subjects. She helps them understand challenging topics, structures lessons clearly, and uses an individual approach to help each student achieve strong results.
Matthew Collins
Matthew Collins is a patient and perceptive tutor who takes great pride in demystifying complex academic concepts for his students. He has a remarkable ability to connect abstract theories to real-world examples, making lessons not only accessible but genuinely engaging. Matthew believes that every student has a unique intellectual rhythm, and he tailors his instruction to match that pace, ensuring no one is left behind. His calm and approachable demeanor creates a safe space for questions, while his high expectations inspire students to push beyond their comfort zones. Through consistent encouragement and clear guidance, Matthew fosters both competence and a lasting curiosity for learning.

Как сделать аккордеон с зависимой картинкой в ZeroBlock Tilda

1
Создали ZeroBlock и добавили туда нужные элементы
2
Для заголовка секции использовали Text и для иконки стрелки Image (задали иконке класс accord-icon)
Объединили два этих элемента в autolayout и задали ему класс accord-trigger
3
Для контентной части создали Text и Image (задали ему класс content-image)
Сам Image сделали видимым только для экранов, когда блок в 1 колонку
Объединили Text и Image в autolayout и задали ему класс accord-content
4
Объединяем заголовочную и контентную секции в autolayout и задали ему класс accord-section
5
Затем создали ещё секций, а потом их все объединили в общий autolayout аккордеона
6
Для боковой картинки создали Image и задали ему класс main-image
7
Вставили код на страницу в блок Т123
Mo-ti Level Up
Видео инструкции по добавлению кода и работе с Zero Block.
Как сделать аккордеон с зависимой картинкой в ZeroBlock Tilda
Фрагмент видео
Библиотека для примера
<script>
document.addEventListener("DOMContentLoaded", function() {
    (function () {
        const accordionMode = 'single';
        const scrollOffset = 60; //отступ при скролле
        const openFirstTab = true; //открыта первая вкладка
        const scrollToActive = true; // включает/отключает скролл
        const scrollRes = 960; // ширина экрана, где работает скролл (0 - везде)

        function shouldScroll() {
            if (!scrollToActive) return false;
            if (scrollRes === 0) return true;
            return window.innerWidth <= scrollRes;
        }

        function scrollToElement(element, delay = 100) {
            if (!element || !shouldScroll()) return;
            
            setTimeout(() => {
                const rect = element.getBoundingClientRect();
                const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                const targetPosition = rect.top + scrollTop - scrollOffset;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
            }, delay);
        }

        function updateMainImage(section, parentRecord) {
            const contentImage = section.querySelector('.accord-content .content-image img');
            if (!contentImage) return;
       
            let imageUrl = contentImage.getAttribute('data-original');
            if (!imageUrl) {
                imageUrl = contentImage.getAttribute('src');
                if (!imageUrl) return; 
            }
            
            const mainImage = parentRecord.querySelector('.main-image img');
            if (!mainImage) return;
            
            if (mainImage.getAttribute('src') === imageUrl) return;
            
            mainImage.style.transition = 'opacity 0.2s ease';
            mainImage.style.opacity = '0';
            
            setTimeout(() => {
                const preloadImg = new Image();
                
                preloadImg.onload = function() {
                    mainImage.setAttribute('data-original', imageUrl);
                    mainImage.setAttribute('src', imageUrl);
                    mainImage.style.opacity = '1';
                };
                
                preloadImg.onerror = function() {
                    mainImage.setAttribute('data-original', imageUrl);
                    mainImage.setAttribute('src', imageUrl);
                    mainImage.style.opacity = '1';
                };
                
                preloadImg.src = imageUrl;
            }, 200);
        }

        function closeSection(section) {
            const content = section.querySelector('.accord-content');
            const icon = section.querySelector('.accord-icon');
            section.classList.remove('accord-open');
            if (content) {
                content.style.height = `${content.scrollHeight}px`;
                content.offsetHeight;
                content.style.height = '0';
            }
            if (icon) {
                icon.style.transform = 'rotateX(0deg)';
            }
        }

        function openSection(section, parentRecord) {
            const content = section.querySelector('.accord-content');
            const icon = section.querySelector('.accord-icon');
            section.classList.add('accord-open');
            if (content) {
                content.style.height = '0';
                content.offsetHeight;
                content.style.height = `${content.scrollHeight}px`;
            }
            if (icon) {
                icon.style.transform = 'rotateX(180deg)';
            }
            updateMainImage(section, parentRecord);
 
            const trigger = section.querySelector('.accord-trigger');
            if (trigger) {
              
                scrollToElement(trigger, 550);
            }
        }

        function updateArtboardHeight(trigger) {
            const artboard = trigger.closest('.t396__artboard');
            if (artboard && artboard.getAttribute('data-artboard-heightmode') === 'hug') {
                if (typeof t396__updateAutoHeight === 'function') {
                    t396__updateAutoHeight(artboard);
                }
            }
        }

        function initAccordionInBlock(block) {
            const triggers = block.querySelectorAll('.accord-trigger');
            const sections = block.querySelectorAll('.accord-section');
            
            if (sections.length === 0) return;

            const sectionsArray = Array.from(sections);

            function closeAllExcept(currentSection) {
                sectionsArray.forEach(section => {
                    if (section !== currentSection && section.classList.contains('accord-open')) {
                        closeSection(section);
                    }
                });
            }

            function openNextAvailableSection(closedSection) {
                if (!openFirstTab) return;
                
                const closedIndex = sectionsArray.indexOf(closedSection);
                let nextIndex = closedIndex + 1;
                
                if (nextIndex >= sectionsArray.length) {
                    nextIndex = 0;
                }
                
                if (nextIndex === closedIndex) return;
                
                const nextSection = sectionsArray[nextIndex];
                openSection(nextSection, block);
                
                const nextTrigger = nextSection.querySelector('.accord-trigger');
                if (nextTrigger) {
                    setTimeout(() => updateArtboardHeight(nextTrigger), 300);
                }
            }

            function initFirstTabInBlock() {
                if (!openFirstTab) return;
                
                const firstSection = sectionsArray[0];
                if (!firstSection) return;
                
                const firstTrigger = firstSection.querySelector('.accord-trigger');
                const firstContent = firstSection.querySelector('.accord-content');
                const firstIcon = firstSection.querySelector('.accord-icon');
                
                firstSection.classList.add('accord-open');
                
                if (firstContent) {
                    setTimeout(() => {
                        firstContent.style.height = `${firstContent.scrollHeight}px`;
                    }, 0);
                }
                
                if (firstIcon) {
                    firstIcon.style.transform = 'rotateX(180deg)';
                }
                
                updateMainImage(firstSection, block);
                
                if (firstTrigger) {
                    updateArtboardHeight(firstTrigger);
                    setTimeout(() => updateArtboardHeight(firstTrigger), 100);
                    setTimeout(() => updateArtboardHeight(firstTrigger), 300);
                    
                    setTimeout(() => scrollToElement(firstTrigger, 500), 800);
                }
                
                window.addEventListener('load', function() {
                    if (firstTrigger) {
                        setTimeout(() => updateArtboardHeight(firstTrigger), 100);
                       
                        setTimeout(() => scrollToElement(firstTrigger, 500), 500);
                    }
                });
            }

            sectionsArray.forEach((section, index) => {
                const content = section.querySelector('.accord-content');
                if (content) {
                    if (index !== 0 || !openFirstTab) {
                        content.style.height = '0';
                    }
                }
            });

            initFirstTabInBlock();

            triggers.forEach(trigger => {
                trigger.addEventListener('click', function(e) {
                    const section = this.closest('.accord-section');
                    if (!section) return;
                    
                    const isOpen = section.classList.contains('accord-open');
                    
                    if (accordionMode === 'single') {
                        closeAllExcept(section);
                    }
                    
                    if (isOpen) {
                        closeSection(section);
                        
                        if (openFirstTab) {
                            setTimeout(() => openNextAvailableSection(section), 50);
                        }
                        
                        setTimeout(() => updateArtboardHeight(this), 300);
                    } else {
                        openSection(section, block);
                        setTimeout(() => updateArtboardHeight(this), 300);
                    }
                });
            });

            sectionsArray.forEach(section => {
                const content = section.querySelector('.accord-content');
                if (content) {
                    content.addEventListener('transitionend', function() {
                        const parentSection = this.closest('.accord-section');
                        if (parentSection) {
                            if (parentSection.classList.contains('accord-open')) {
                                this.style.height = '';
                            } else {
                                this.style.height = '0';
                            }
                            const trigger = parentSection.querySelector('.accord-trigger');
                            if (trigger) updateArtboardHeight(trigger);
                        }
                    });
                }
            });
        }

        const allBlocks = document.querySelectorAll('.t-rec');
        
        allBlocks.forEach(block => {
            const hasTriggers = block.querySelector('.accord-trigger');
            const hasSections = block.querySelector('.accord-section');
            
            if (hasTriggers && hasSections) {
                initAccordionInBlock(block);
            }
        });
       
        let resizeTimeout;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
               
                if (shouldScroll()) {
                 
                    document.querySelectorAll('.accord-section.accord-open').forEach(section => {
                        const trigger = section.querySelector('.accord-trigger');
                        if (trigger) {
                          
                            scrollToElement(trigger, 300);
                        }
                    });
                }
            }, 500);
        });

    })();    
});
</script>


<style>
.accord-icon {
  transition: transform 0.3s ease;
}
.accord-content {
    overflow: hidden;
    transition: height 0.5s ease, transform 0.3s ease 0.2s;
    height: 0;
    transform: translateY(15px);
}
.accord-trigger {
  cursor: pointer;
}
.accord-open .accord-content {
    transform: translateY(0);
}
.main-image img {
    transition: opacity 0.2s ease;
}
</style>
Made on
Tilda