最近公司項目,做微信端用到texarea 需要實現自適應高度的功能
當然自適應高度的方法很多網上找一大片,最直接的方式就是在使用到texarea的controller中添加js代碼事件來實現,這中方式是比較麻煩用到一處就要添加一次
我們既然用到 ionic(angular)就要以ionic的思維去做東西,ionic提供了一個強大的功能就是 directive 自定義指定,這個功能爽炸天了,可以通過dom元素上的屬性監聽
dom從而實現對Dom的修改,以下是實現方式:
js,代碼
//給有自適應高度的textarea添加事件
app.directive('textareaAuto', function ($timeout) {
    return {
     restrict: 'A',
     link: function(scope, element, attr) {
         console.log(element[0].nodeName)
             //判斷是否是    TEXTAREA
       if("TEXTAREA"==element[0].nodeName&&attr.textareaAuto){
         //自適應高度
                 $(element).autoTextarea() 
           }
         }
    };
});
html頁面:
<textarea type="text" textarea-auto="true" rows="1" data-id="{{report.id}}" datatypes="{{report.type}}"> </textarea>


其中textarea-auto為自定義指令 如果項目中任何地方用需要自適應高度只要添加 textarea-auto="true" z指令即可
$(element).autoTextarea() //至二個是自定義的一個插件可以在網上搜以下很多的,如果有需要可以留言
                       
