我想使textarea的高度等于它的文本的高度(并删除滚动条)
HTML
<textarea id="note">SOME TEXT</textarea>
CSS
textarea#note {
width:100%;
direction:rtl;
display:block;
max-width:100%;
line-height:1.5;
padding:15px 15px 30px;
border-radius:3px;
border:1px solid #F7E98D;
font:13px Tahoma, cursive;
transition:box-shadow 0.5s ease;
box-shadow:0 4px 6px rgba(0,0,0,0.1);
font-smoothing:subpixel-antialiased;
background:linear-gradient(#F9EFAF, #F7E98D);
background:-o-linear-gradient(#F9EFAF, #F7E98D);
background:-ms-linear-gradient(#F9EFAF, #F7E98D);
background:-moz-linear-gradient(#F9EFAF, #F7E98D);
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
}
JsFiddle: http://jsfiddle.net/Tw9Rj/
杰斯菲德尔
textarea#note {
width:100%;
direction:rtl;
display:block;
max-width:100%;
line-height:1.5;
padding:15px 15px 30px;
border-radius:3px;
border:1px solid #F7E98D;
font:13px Tahoma, cursive;
transition:box-shadow 0.5s ease;
box-shadow:0 4px 6px rgba(0,0,0,0.1);
font-smoothing:subpixel-antialiased;
background:-o-linear-gradient(#F9EFAF, #F7E98D);
background:-ms-linear-gradient(#F9EFAF, #F7E98D);
background:-moz-linear-gradient(#F9EFAF, #F7E98D);
background:-webkit-linear-gradient(#F9EFAF, #F7E98D);
background:linear-gradient(#F9EFAF, #F7E98D);
height:100%;
}
html{
height:100%;
}
body{
height:100%;
}
或javascript
var s_height = document.getElementById('note').scrollHeight;
document.getElementById('note').setAttribute('style','height:'+s_height+'px');
杰斯菲德尔
对于那些用Angular JS完成这个任务的人,我使用了一个指令
HTML:
<textarea elastic ng-model="someProperty"></textarea>
JS:
.directive('elastic', [
'$timeout',
function($timeout) {
return {
restrict: 'A',
link: function($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function() {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
$timeout将一个事件排队,该事件将在DOM加载后触发,这是获得正确的scrollHeight所必需的(否则您将得到undefined)