ฉันกำลังกรอก textarea ที่มีเนื้อหาเพื่อให้ผู้ใช้แก้ไข
เป็นไปได้ไหมที่จะทำให้มันยืดออกเพื่อให้พอดีกับเนื้อหาด้วย CSS (เช่นoverflow:showdiv)
ฉันกำลังกรอก textarea ที่มีเนื้อหาเพื่อให้ผู้ใช้แก้ไข
เป็นไปได้ไหมที่จะทำให้มันยืดออกเพื่อให้พอดีกับเนื้อหาด้วย CSS (เช่นoverflow:showdiv)
คำตอบ:
ไม่จริง. โดยปกติจะทำได้โดยใช้จาวาสคริปต์
มีการอภิปรายที่ดีเกี่ยวกับวิธีการทำที่นี่ ...
หนึ่งบรรทัดเท่านั้น
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
this.scrollHeight + "px"เพื่อthis.scrollHeight + 3 +  "px"ทำให้พื้นที่ข้อความใหญ่พอที่จะไม่แสดงแถบเลื่อน
                    นี่คือฟังก์ชั่นที่ใช้งานได้กับ jQuery (สำหรับความสูงเท่านั้นไม่ใช่ความกว้าง):
function setHeight(jq_in){
    jq_in.each(function(index, elem){
        // This line will work with pure Javascript (taken from NicB's answer):
        elem.style.height = elem.scrollHeight+'px'; 
    });
}
setHeight($('<put selector here>'));
หมายเหตุ: ฝ่ายปฏิบัติการขอวิธีแก้ปัญหาที่ไม่ใช้ Javascript แต่สิ่งนี้น่าจะเป็นประโยชน์กับหลาย ๆ คนที่เจอคำถามนี้
นี่เป็นวิธีแก้ปัญหาที่ง่ายมาก แต่ใช้ได้กับฉัน:
<!--TEXT-AREA-->
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>
<!--JAVASCRIPT-->
<script type="text/javascript">
function setHeight(fieldId){
    document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
}
setHeight('textBox1');
</script><style>   textarea {     resize: none;     overflow: auto;   } </style>  <!--TEXT-AREA--> <textarea onkeyup="setHeight.call(this);">Hello World</textarea>  <!--JAVASCRIPT--> <script type="text/javascript"> function setHeight(){     this.style.height = '1px';     this.style.height = this.scrollHeight + 'px'; } </script>โดยทั่วไปคุณต้องตั้งค่าความสูงเป็น 1px ก่อนเนื่องจากสิ่งนี้: stackoverflow.com/questions/10722058/…
                    อีกวิธีง่ายๆสำหรับการควบคุมพื้นที่ข้อความแบบไดนามิก
<!--JAVASCRIPT-->
<script type="text/javascript">
$('textarea').on('input', function () {
            this.style.height = "";
            this.style.height = this.scrollHeight + "px";
 });
</script>