Задача такая. Что-бы при нажатии на кнопку "читать больше" <div>
менял высоту на высоту всего текста, а при нажатии еще раз сворачивался обратно. Высота неизвестна (текста может быть сколько угодно). Минимальная высота - 160px
.
Пытался решить следующим способом:
/*-------- READ MORE --------*/
var rowsContent = document.querySelector('p');
var content = document.querySelector('.content');
var contentHeight = document.querySelector('.content').clientHeight;
var button = document.getElementById('readMore');
var startHeight = 160;
var h = 1;
var text = rowsContent.textContent;
var span = document.createElement('span');
span.textContent = text;
rowsContent.innerHTML = '';
rowsContent.appendChild(span);
function calcRowCount() {
if (span.getClientRects().length >= 4) {
button.style.display = "block";
content.classList.add("isActive");
} else {
button.style.display = "none";
}
}
calcRowCount();
button.onclick = function(){
var intervalID=setInterval(showHide(),10);
};
function showHide(){
if (startHeight>contentHeight) {
startHeight -= h;
content.style.height = startHeight +"px";
if(startHeight<=160){
clearInterval(showHide());
startHeight = 160;
}
}
else{
startHeight += h;
content.style.height = startHeight +"px";
if(startHeight<contentHeight){
clearInterval(showHide());
startHeight = contentHeight;
}
}
}
.content.isActive{
height: 160px;
display: block;
}
.content
{
transition: 30ms;
margin: 20px 0;
font-size: 16px;
line-height: 1.6;
color: #505050;
overflow: hidden;
}
<div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<span id="readMore">
читать больше
</span>