2016-11-24 45 views
2

如果您編寫文本,textarea的大小會增加,但是如果刪除此文本,則不會發生任何情況。如果您要刪除文字,是否可以動態降低textarea的高度?刪除文本後調整文本大小

$('textarea').on('input', function() { 
 
    var scrollHeight = parseInt($(this).prop('scrollHeight')); 
 
    $(this).height(scrollHeight); 
 
});
.OuterDiv 
 
{ 
 
    width:200px; 
 
    height:300px; 
 
    border:1px solid #000; 
 
    position:relative; 
 
    bottom:0; 
 
} 
 
.text 
 
{ 
 
    resize:none; 
 
    width:198px; 
 
    height:45px; 
 
    max-height:145px; 
 
    background-color:rgba(90,90,180,1); 
 
    font-size:16px; 
 
    font-family:Arial; 
 
    overflow-y:auto; 
 
    padding:0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="OuterDiv"> 
 
    <textarea class="text" placeholder="Write some text..."></textarea> 
 
</div>

回答

5

設置height風格代替正確ty,並使用初始高度以始終從45px開始。

$('textarea').on('input', function() { 
 
    $(this).css('height', "45px"); 
 
    $(this).css('height', this.scrollHeight+"px"); 
 
});
.OuterDiv 
 
{ 
 
    width:200px; 
 
    height:300px; 
 
    border:1px solid #000; 
 
    position:relative; 
 
    bottom:0; 
 
    } 
 
.text 
 
{ 
 
    resize:none; 
 
    width:198px; 
 
    height:45px; 
 
    max-height:145px; 
 
    background-color:rgba(90,90,180,1); 
 
    font-size:16px; 
 
    font-family:Arial; 
 
    overflow-y:auto; 
 
    padding:0; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="OuterDiv"> 
 
    <textarea class="text" placeholder="Write some text..."></textarea> 
 
</div>

1

你可以使用一個div contentEditable相反,它會自動調整大小取決於contentno需要任何腳本:

.OuterDiv 
 
{ 
 
    width:200px; 
 
    height:300px; 
 
    border:1px solid #000; 
 
    position:relative; 
 
    bottom:0; 
 
} 
 
.text 
 
{ 
 
    resize:none; 
 
    width:198px; 
 
    min-height:45px; 
 
    height:auto; 
 
    max-height:145px; 
 
    background-color:rgba(90,90,180,1); 
 
    font-size:16px; 
 
    font-family:Arial; 
 
    overflow-y:auto; 
 
    padding:0; 
 
} 
 

 
[contenteditable=true]:empty:before{ 
 
    content: attr(placeholder); 
 
    display: block; /* For Firefox */ 
 
    color: grey; 
 
}
<div class="OuterDiv"> 
 
    <div class="text" contentEditable="true" placeholder="Write some text..."></div> 
 
</div>