AngularJS <input> 输入框自适应内容宽度

在Gist上找到的一个directive,用来让input输入框的宽度自适应内容宽度。
https://gist.github.com/mbenford/8016984

原理是生成一个相同样式的,隐藏的span,通过span的宽度动态改变input的宽度。
同时兼顾了input有placeholder的情况。

如果是在比较大的系统中,可以用throttle节流阀包装一下resize方法,避免性能问题。

如果是textarea,对应的directive在这里:
https://github.com/monospaced/angular-elastic

效果:

See the Pen input auto size directive by iMaeGoo (@iMaeGoo) on CodePen.

HTML
1
2
3
4
<div ng-app="Test" ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input type="text" ng-model="name" placeholder="type here" autosize/>
</div>
JS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var app = angular.module('Test', []);

app.controller('MainCtrl', function ($scope) {
$scope.name = '';
});

app.directive('autosize', function ($document) {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var span;

span = angular.element('<span></span>');
span.css('display', 'none')
.css('width', 'auto');

element.parent().append(span);

function resize(value) {
var style = getComputedStyle(element[0]);
span.css('font', style.font)
.css('letter-spacing', style.letterSpacing)
.css('word-spacing', style.wordSpacing)
.css('padding', style.padding);

if (value != null && value.length === 0) {
value = element.attr('placeholder') || '';
}
span.text(value);
span.css('display', '');
try {
element.css('width', span.prop('offsetWidth') + 'px');
}
finally {
span.css('display', 'none');
}
};

ctrl.$parsers.unshift(function (value) {
resize(value);
return value;
});

ctrl.$formatters.unshift(function (value) {
resize(value);
return value;
});
}
};
});

AngularJS <input> 输入框自适应内容宽度

https://www.imaegoo.com/2019/ajs-auto-width-input/

作者

iMaeGoo

发布于

2019-04-17

更新于

2019-04-17

许可协议

CC BY 4.0

评论