Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Спойлер / Подкат от трёх строк (https://javascript.ru/forum/jquery/85280-spojjler-podkat-ot-trjokh-strok.html)

Cleo 05.06.2023 10:05

Спойлер / Подкат от трёх строк
 
Привет!
Подскажите кто-нибудь пожалуйста как быть?

У меня список вот из таких пунктов

Код:

<div className="xitem">
        <div className="main">
            <div className="tag">test</div>
            <div className="value">Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
                took a galley of type and scrambled it to make a type specimen book. It has survived not only five
                centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
        </div>
</div>


Нужно чтобы при открытии было видно только 3 строки а при клике на пункт он плавно на весь текст разворачивался. =(

вот что пока есть

const items = document.querySelectorAll('.xitem');

    items.forEach(item => {
        item.addEventListener('click', function() {
            items.forEach(elem => elem.classList.remove('active'));
            this.classList.add('active');

            $(this).find('.value').css({'max-height':'3em'});
            $(this).find('.value').css({'height':'3em'});


            $(this).find('.value').slideToggle( "slow", function() {

                $(this).find('.value').css({'max-height':'10em'});
                $(this).find('.value').css({'height':'10em'});

            });

        });
    });

рони 05.06.2023 10:21

Цитата:

Сообщение от Cleo
className

???

Cleo 05.06.2023 10:23

Цитата:

Сообщение от рони (Сообщение 552284)
???

сорри.. ну просто у меня там класс конечно... случайно тут так написал

Cleo 05.06.2023 10:24

это мне редактор автозаменой направил

рони 05.06.2023 10:40

Спойлер открытие блока на всю его высоту
 
Cleo,

<!DOCTYPE HTML>
<html>

<head>
    <title>Untitled</title>
    <meta charset="utf-8">
    <style type="text/css">
        .xitem {
            width: 250px;
        }

        .value {
            max-height: 3em;
            overflow: hidden;
            transition: max-height 1s;
        }

        .xitem.active .value {
            max-height: var(--h);
        }
    </style>
</head>

<body>
    <div class="xitem">
        <div class="main">
            <div class="tag">test</div>
            <div class="value">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
        </div>
    </div>
    <div class="xitem">
        <div class="main">
            <div class="tag">test</div>
            <div class="value">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
        </div>
    </div>
    <div class="xitem">
        <div class="main">
            <div class="tag">test</div>
            <div class="value">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
                book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
            </div>
        </div>
    </div>
    <script>
        const items = document.querySelectorAll('.xitem');
        items.forEach(item => {
            item.addEventListener('click', (event) => {
                if (event.target.closest('.tag'))
                    items.forEach(el => el == item ? el.classList.toggle('active') : el.classList.remove('active'))
            })
            let h = item.querySelector('.value').scrollHeight;
            item.style.setProperty('--h', `${h}px`)
        })
    </script>
</body>

</html>

Cleo 05.06.2023 10:47

Большое спасибо! :dance: вы просто умничка :victory:

вижу способ другой но сейчас буду разбираться :write:

Cleo 05.06.2023 14:53

Рони ещё раз большое спасибо!

код классный вот только одна проблема
получаю вот let h = item.querySelector('.value').scrollHeight;
высоту value далее её передаю

в ФФ всё хорошо а вот хром иногда строку напополам режет(( не хватает высоты((

по ширине всё выровнено.. кол-во слов в строке одинаковое.. но высота получается в разных браузерах разная =( в чём может быть проблема?
вы с этим кодом работали.. знаете наверняка в чём минус =(

рони 05.06.2023 15:54

Cleo,
возможно в вашем коде есть картинки, где-то они закешировались как в ФФ, а где-то ещё нет, и надо тогда обернуть весь код так

window.addEventListener('load', () => {
           // сюда весь код js
        })

Cleo 05.06.2023 16:18

КРУУУУТО!!!!:dance: получилось! большущие спасибо!!

Cleo 08.06.2023 04:53

Цитата:

Сообщение от рони (Сообщение 552290)
Cleo,
возможно в вашем коде есть картинки, где-то они закешировались как в ФФ, а где-то ещё нет, и надо тогда обернуть весь код так

window.addEventListener('load', () => {
           // сюда весь код js
        })

Рони ещё здравствуйте)) можно я вас опять немного отвлеку??

Посмотрите пожалуйста небольшая проблемка возникла..
если на телефоне меняешь ориентацию с горизонтального режима на вертикальный или наоборот то спойлер не работает...
в общем будет работать только в том режиме который был при загрузке.. что собственно логично тк у нас евент Load
я сделал вот так на ориентайшенЧендж:

function spoiler() {
        const items = document.querySelectorAll('.tagitem');
        items.forEach(item => {
            item.addEventListener('click', (event) => {
                if (event.target.closest('.value'))
                    items.forEach(el => el == item ? el.classList.toggle('active') : el.classList.remove('active'))
            })
            let h = item.querySelector('.value').scrollHeight;
            item.style.setProperty('--value_height', `${h}px`);

        });
    }


    window.addEventListener('load', () => {
        spoiler();
    });

    window.addEventListener('orientationchange', () => {
        spoiler();
    });


Но всё равно почему то не работает =( в чём тут может быть проблема? =(


Часовой пояс GMT +3, время: 21:48.