gpt4 book ai didi

javascript - Angularjs - 文本区域自动增长

转载 作者:行者123 更新时间:2023-11-27 22:45:33 25 4
gpt4 key购买 nike

我想用这个directive在我的项目中,但我希望文本区域在加载内容时扩展。

Angular-Autogrow.js:

(function(){
'use strict';
angular.module('angular-autogrow', []).directive('autogrow', ['$window', function($window){
return {
link: function($scope, $element, $attrs){

/**
* Default settings
*/
$scope.attrs = {
rows: 1,
maxLines: 999
};

/**
* Merge defaults with user preferences
*/
for(var i in $scope.attrs){
if($attrs[i]){
$scope.attrs[i] = parseInt($attrs[i]);
}
}

/**
* Calculates the vertical padding of the element
* @returns {number}
*/
$scope.getOffset = function(){
var style = $window.getComputedStyle($element[0], null),
props = ['paddingTop', 'paddingBottom'],
offset = 0;

for(var i=0; i<props.length; i++){
offset += parseInt(style[props[i]]);
}
return offset;
};

/**
* Sets textarea height as exact height of content
* @returns {boolean}
*/
$scope.autogrowFn = function(){
var newHeight = 0, hasGrown = false;
if(($element[0].scrollHeight - $scope.offset) > $scope.maxAllowedHeight){
$element[0].style.overflowY = 'scroll';
newHeight = $scope.maxAllowedHeight;
}
else {
$element[0].style.overflowY = 'hidden';
$element[0].style.height = 'auto';
newHeight = $element[0].scrollHeight - $scope.offset;
hasGrown = true;
}
$element[0].style.height = newHeight + 'px';
return hasGrown;
};

$scope.offset = $scope.getOffset();
$scope.lineHeight = ($element[0].scrollHeight / $scope.attrs.rows) - ($scope.offset / $scope.attrs.rows);
$scope.maxAllowedHeight = ($scope.lineHeight * $scope.attrs.maxLines) - $scope.offset;

$element[0].addEventListener('input', $scope.autogrowFn);
/**
* Auto-resize when there's content on page load
*/
if($element[0].value != ''){
$scope.autogrowFn();
}
}
}
}]);
})();

我改变:

// $element[0].addEventListener('input', $scope.autogrowFn);

$element[0].addEventListener('load', $scope.autogrowFn);//<-- I add this line

但是没有成功。如何更改它以便加载内容时文本区域自动展开?

最佳答案

嗨,您必须先使用该指令,然后在 app.js 中包含“angularjs-autogrow”指令,然后检查文本区域是否会根据您的输入自动增长

HTML

<textarea autogrow></textarea>

JS

var app = angular.module('plunker', ["angularjs-autogrow"]);

app.controller('MainCtrl', function($scope) {

});

供引用https://plnkr.co/edit/kj3ikS30cqVIRofTU22X?p=preview

关于javascript - Angularjs - 文本区域自动增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38428299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com