В НТМЛ верх:
Код:
<!-- Сворачивание постов при определенной высоте. Стиль в НТМЛ верх -->
<style>
/* высота свернутого контента */
.post-content.toggle-content .post-text {
overflow: hidden;
max-height: 8.5em;
position: relative;
transition: max-height 0.25s ease;
}
/* затемнение снизу */
.post-content.toggle-content .post-text::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3em; /* высота затемнения */
pointer-events: none;
/* градиент */
background: linear-gradient(
to bottom,
rgba(255,255,255,0) 0%,
rgba(255,255,255,0.8) 60%,
rgba(255,255,255,1) 100%
);
}
/* убираем затемнение при раскрытии */
.post-content.expanded-content .post-text::after {
display: none;
}
.post-content.expanded-content .post-text {
overflow: visible;
}
.post-toggle-content {
display: block;
cursor: pointer;
margin-top: 5px;
color: #888;
}
</style>
В НТМЛ низ:
Код:
<!-- Сворачивание постов при определенной высоте. Скрипт в самый низ НТМЛ низа -->
<script>
$(function () {
// задаем высоту, при которой происходит сворачивание
const MAX_HEIGHT = 140;
$('.topic .post-content').each(function () {
const $content = $(this);
if ($content.data('ready')) return;
$content.data('ready', 1);
// создаём контейнер текста
let $text = $('<div class="post-text"></div>');
$content.contents().each(function () {
if (
this.nodeType === 3 ||
(this.nodeType === 1 && !$(this).hasClass('post-sig'))
) {
$text.append(this);
}
});
$content.prepend($text);
const el = $text[0];
if (!el) return;
// функция проверки высоты
function checkHeight() {
if (el.scrollHeight > MAX_HEIGHT) {
$content.addClass('toggle-content');
if (!$content.children('.post-toggle-content').length) {
$content.append(
'<span class="post-toggle-content">Развернуть</span>'
);
}
}
}
// первичная проверка
checkHeight();
// отслеживание загрузки картинок
$text.find('img').each(function () {
if (!this.complete) {
$(this).on('load', checkHeight);
}
});
// отслеживание любых изменений размера (лучшее решение)
if (window.ResizeObserver) {
const ro = new ResizeObserver(checkHeight);
ro.observe(el);
}
});
// клик
$(document).on('click', '.post-toggle-content', function (e) {
e.stopPropagation();
const $btn = $(this);
const $content = $btn.closest('.post-content');
const $text = $content.find('.post-text');
// сброс перед измерением (фикс "не с первого раза")
$text[0].style.maxHeight = 'none';
if ($content.hasClass('expanded-content')) {
$text.css('max-height', '8.5em');
$content.removeClass('expanded-content');
$btn.text('Развернуть');
} else {
const fullHeight = $text[0].scrollHeight;
$text.css('max-height', fullHeight + 'px');
$content.addClass('expanded-content');
$btn.text('Свернуть');
}
});
});
</script>
Скрипт ставить ниже всех скриптов, которые влияют на посты.