评论框自动控制高度(原生JavaScript)
该Demo可以根据用户输入的高度自动切换两种高度
效果如图:
HTML
<div class="cont_comment_cont">
<div id="textareaHeight">
<textarea id="textarea" placeholder="在此输入评论内容~"></textarea>
</div>
<div>发布</div>
</div>
CSS
/* textarea配置 */
textarea {
padding: 0;
margin: 0;
list-style: none
}
textarea::-webkit-input-placeholder,
textarea:-moz-placeholder,
textarea::-moz-placeholder,
textarea:-ms-input-placeholder {
color: #CFD0D1 !important;
}
/* 整体控制 */
.cont_comment_cont {
display: flex;
justify-content: center;
align-items: flex-start;
}
/* 评论框样式 */
.cont_comment_cont>div:nth-child(1) {
padding: 20px 16px 20px 20px;
width: 698px;
height: 25px;
border-radius: 5px;
border: 0;
background-color: #F0F3F5;
}
/* 富文本框样式 */
.cont_comment_cont textarea {
width: 702px;
height: 100%;
font-size: 18px;
font-family: PingFang SC;
font-weight: 400;
line-height: 25px;
color: #050E26;
border-radius: 5px;
resize: none;
border: 0;
background-color: #F0F3F5;
outline: none;
overflow-y: hidden;
}
/* 按钮样式 */
.cont_comment_cont>div:nth-child(2) {
width: 126px;
height: 65px;
background: rgba(80, 94, 255, 1);
border-radius: 5px;
background-color: #505EFF;
font-size: 20px;
font-family: PingFang SC;
font-weight: 500;
color: #FFFFFF;
text-align: center;
line-height: 65px;
margin-left: 20px;
}
JavaScript
// 调整评论高度
let textareaHeight = document.querySelector('#textareaHeight')
let textarea = document.querySelector('#textarea')
textarea.addEventListener('input', function (e) {
textareaHeight.style.height = '25px'
if (e.target.scrollHeight > 25) {
textareaHeight.style.height = '52px'
} else {
textareaHeight.style.height = '25px'
}
})