[英]Autosize a textarea without focus
目前,我有以下代碼可以自動執行我的textarea:
$('textarea').bind('input propertychange', function() {
$(this).height(50).height(Math.min(370, this.scrollHeight));
});
當我在文本區域並通過按一些鍵更改文本時,此方法效果很好。
我需要的是在通過JavaScript設置區域文本時以及文本區域未聚焦時可以執行相同操作的可能性。 僅在回調中執行相同的代碼(當然具有正確的作用域)不起作用-高度為零。
您可以嘗試觸發事件
$('textarea').on('input propertychange', function() {
$(this).height(50).height(Math.min(370, this.scrollHeight));
});
$('textarea').trigger('propertychange');
//如果您使用html()更改textarea內容或追加內容,則可以嘗試類似$('textarea')。html(somecontent); $('textarea')。height($('textarea')。scrollHeight);
執行回調函數后,觸發propertychange函數
$('textarea').trigger('propertychange');
有change
和trigger
$("#i").on('change', function(){ this.style.color = 'red'; }); function f(){ $('#i').trigger('change'); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="i" value="hello" /><br> <button onclick="f()">Run</button>
我的jQuery解決方案是:
$(document).ready(function(){
$("textarea").each(function(){
$(this).height(($(this)[0].scrollHeight) + "px");
});
$("textarea").keypress(function(){
$(this).height(($(this)[0].scrollHeight) + "px");
});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.