Определение количества выводимых строк в зависимости от длины текста
задача: есть 2 элемента div с названием и описанием. если название полностью вмещается в 4 строки, то под описание отводится 12, иначе название занимает 8 строк и описание занимает также 8 строк с многоточием в конце при переполнении
варианты, к которым приходил:
- можно было бы поиграться с flex-grow, но display: -webkit-box из-за line-clamp (усекает текст на определенное количество строк) - не подходит
- ориентироваться на количество символов в строке не получится, ибо в используемом шрифте не все символы имеют одинаковую ширину
вопрос: знаю, как можно высчитать количество строк после отображения (высота элемента / высоту строки; вариант со скрытым элементом), но мне нужно применить стили к элементам до их отображения, а не по какой-либо кнопке, что делать?
Ответы (1 шт):
Автор решения: Miha
→ Ссылка
Вот какой код мне удалось придумать, но он может быть неточным, так как значения для line-height
может быть разным у разных шрифтов
const articles = document.querySelectorAll('.article');
articles.forEach(article => {
const header = article.querySelector('.header');
const content = article.querySelector('.content');
const headerStyle = window.getComputedStyle(header, null);
const headerBoxSizing = headerStyle.getPropertyValue('box-sizing');
const headerFontSize = parseInt(headerStyle.getPropertyValue('font-size'));
let headerLineHeader = parseInt(headerStyle.getPropertyValue('line-height'));
let headerHeight = parseInt(headerStyle.getPropertyValue('height'));
if (isNaN(headerLineHeader)) {
// Значения по умолчанию для line-height это 1.2
headerLineHeader = headerFontSize * 1.2;
}
if (headerBoxSizing === 'border-box') {
const paddingTop = parseInt(headerStyle.getPropertyValue('padding-top'));
const paddingBottom = parseInt(headerStyle.getPropertyValue('padding-bottom'));
const borderTop = parseInt(headerStyle.getPropertyValue('border-top-width'));
const borderBottom = parseInt(headerStyle.getPropertyValue('border-bottom-width'));
headerHeight = headerHeight - paddingTop - paddingBottom - borderTop - borderBottom;
}
const lines = Math.ceil(headerHeight / headerLineHeader);
switch (lines) {
case 4:
content.style.setProperty('--line-clamp', 12);
break;
case 3:
content.style.setProperty('--line-clamp', 8);
break;
case 2:
content.style.setProperty('--line-clamp', 4);
break;
}
});
*,
*:after,
*:before {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
width: 100%;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
display: grid;
gap: 36px;
grid-template-columns: repeat(1, minmax(0, 1fr));
}
.article {
box-shadow: 0 0 4px 2px rgba(0, 0, 0, .1);
padding: 6px 12px;
}
.article .content {
--line-clamp: 3;
display: -webkit-box;
-webkit-line-clamp: var(--line-clamp);
-webkit-box-orient: vertical;
overflow: hidden
}
@media (min-width: 768px) {
.container {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (min-width: 1024px) {
.container {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 1536px) {
.container {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
<div class="container">
<div class="article">
<h1 class="header">1<br />2<br />3<br />4<br /></h1>
<p class="content">On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and
equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is
untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently
occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse
pains.
</p>
</div>
<div class="article">
<h1 class="header">1<br />2<br />3</h1>
<p class="content">On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and
equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is
untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently
occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse
pains.
</p>
</div>
<div class="article">
<h1 class="header">1<br />2</h1>
<p class="content">On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and
equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is
untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently
occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse
pains.
</p>
</div>
</div>