很多前端開發的朋友可能都會遇到textarea 輸入框的高度不能自動隨着用戶的輸入變化的問題,今兒小生也遇到了, 並通過網絡上的信息解決了這個問題,於是將解決方法貼上,以作備忘。
directiveApp.directive('autoHeight', function(){ function autoHeight(elem){ elem.style.height = 'auto'; elem.scrollTop = 0; //防抖動 elem.style.height = elem.scrollHeight + 'px'; } return { scope: {}, link: function (scope, ele, attrs) { var oriEle = $(ele).get(0); $(oriEle).focus(); $(oriEle).bind('keyup click', function(e) { autoHeight($(this).get(0)); }); var timer = setInterval(function(){ if($(oriEle).val()) { autoHeight(oriEle); clearInterval(timer); } }, 100); } }; });
Html code: <textarea auto-height></textarea>
不才,望諒。