本文主要是介绍前端-jquery文本高度自适应-textarea,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方案1:
$("#theId").height($("#theId")[0].scrollHeight);$("#theId").on("keyup keydown", function() {$(this).height(this.scrollHeight);})
这样做可以高度自适应,但是重新回来,输入的时候,高度不会恢复。
方案2:
//jQuery实现textarea高度根据内容自适应
$.fn.extend({txtaAutoHeight: function() {return this.each(function() {var $this = $(this);if (!$this.attr('initAttrH')) {$this.attr('initAttrH', $this.outerHeight());}setAutoHeight(this).on('input', function() {setAutoHeight(this);});});function setAutoHeight(elem) {var $obj = $(elem);return $obj.css({height: $obj.attr('initAttrH'),'overflow-y': 'hidden'}).height(elem.scrollHeight);}}
});
$('#theId').txtaAutoHeight()
这个也可以高度自适应,但是同样回来要重新输入的时候,高度不会恢复。但是开始输入后就恢复高度了。
只有在tab切换,或者hide,show的时候会出现这种情况,解决方案:初始给定一个高度。
html中
min-height: 2rem
js中
$('#txtInput').css("height", 30);
$('#txtInput2').css("height", 30);
解决。
这篇关于前端-jquery文本高度自适应-textarea的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!