23:10, 17-дек-2023
Скрипт для автоматической подстройки высоты тега формы textarea в зависимости от вводимого внутри текста
Добавляем на свою страницу, HTML:
<textarea rows="1">Текст внутри textarea</textarea>
Добавляем в CSS:
textarea {
resize: none;
&.auto {
overflow-y: hidden;
}
}
textarea {
-webkit-appearance: none;
box-sizing: border-box;
outline: none;
width: 100%;
max-width: 240px;
font-size: 14px;
font-family: "Inter";
line-height: 22px;
padding: 16px 20px;
border-radius: 15px;
color: #404660;
border: none;
background: #fff;
transition: box-shadow 0.25s;
box-shadow: inset 0 0 0 1px var(--border-color, #e1e6f9),
0 0 0 3px var(--focus-color, transparent);
&:focus {
--focus-color: #eceffc;
}
&:focus,
&:hover {
--border-color: #bbc1e1;
}
}
Добавляем JS:
document.querySelectorAll('textarea').forEach(el => {
el.style.height = el.setAttribute('style', 'height: ' + el.scrollHeight + 'px');
el.classList.add('auto');
el.addEventListener('input', e => {
el.style.height = 'auto';
el.style.height = (el.scrollHeight) + 'px';
});
});
Пример на отдельной страничке: перейти
Похожие новости