實作了能偵測 textarea 內容並自動調整高度的 angularjs directive。
當 <textarea> 裡的文字變多需要高多行的 textarea 時,即需要更高的 textrea 時,
可以自動的調高高度,
而當文字變少時也能自動減少高度。
Note:
因為有使用到一些 jQuery 的 function,例如 innerHeight,所有需要先 include jQuery
直接上程式碼及範例:
html:<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> This <textarea> will change its height to contain content. <div ng-app="app" ng-controller="controller as ctrl"> <textarea textarea-auto-resizer></textarea> </div>
angular.module("app", [])
.controller("controller", ["$scope", function($scope) {
var self = this;
self.text = "long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words - long words"
}])
.directive('textareaAutoResizer', ["$sce", function($sce) {
return {
link: function(scope, element, attrs, ngModel) {
autoResizeTextArea();
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
autoResizeTextArea();
});
element.on("input", autoResizeTextArea);
function autoResizeTextArea(event) {
var dom = angular.element(element);
dom.css({
height: ""
});
if (dom.prop("scrollHeight") > dom.innerHeight()) {
//set dom height(without padding part) to scrollHeight - padding part
dom.height(dom.prop("scrollHeight") - (dom.innerHeight() - dom.height()));
}
}
}
};
}]);
參考:
沒有留言 :
張貼留言