我是css和html的新手。我使用textarea讓用戶輸入多行內(nèi)容,這是我所做的最少的代碼來顯示我所面臨的問題,App.tsx代碼如下所示:
import React, { useState } from "react";
const App: React.FC = () => {
const [promptLines, setPromptLines] = useState<number>(1);
const handleChange = (e: any) => {
const inputContent = e.target.value;
if (inputContent && inputContent.length > 0) {
const talkInput = document.getElementById("talkInput");
if(!talkInput) return;
const lineHeight = parseInt(window.getComputedStyle(talkInput).getPropertyValue('line-height'));
talkInput.style.cssText = 'line-height: 23px;';
const scrlht = talkInput.scrollHeight;
const lines = Math.floor(scrlht / lineHeight);
console.log(lines);
}
}
return (
<div className="outerdiv">
<textarea
id="talkInput"
rows={promptLines ? promptLines : 1}
onChange={handleChange}></textarea>
</div>
);
}
export default App;
這是App.css css文件的樣子:
.outerdiv{
display: flex;
align-items: center;
padding: 10px;
border-radius: 25px;
border: 2px solid #ccc;
transition: border-color 0.5s ease;
width: 80%;
margin: auto;
margin-bottom: 15px;
margin-top: 10px;
box-sizing: border-box;
min-height: 40px;
}
.outerdiv textarea{
flex: 1;
border: none;
border-radius: 25px;
outline: none;
font-size: 16px;
font-family: sans-serif;
resize: none;
padding: 6px;
min-height: 23px;
line-height: 23px;
height: 1rem;
}
當(dāng)我將內(nèi)容輸入到textarea中時,行數(shù)將會增加,當(dāng)我從textarea中刪除contnet時,行數(shù)將會減少,所有事情都按預(yù)期工作,但是最少的行數(shù)是3。它不會減少少于3行。為什么scrollHeight在3行高度停止下降?有沒有可能讓scrollHeight繼續(xù)降低直到1行?
下面是一個用div代替textarea的例子,contentEditable = & quottrue & quot。這是你需要的嗎?
.my-div {
width: 200px;
border:1px solid black;
min-height: 20px;
max-height:100px;
overflow-y: auto
}
<div contentEditable="true" class="my-div"></div>