简单的jQuery textarea扩展以适合内容 [英] Simple jQuery textarea expand to fit content
问题描述
在尝试构建一个简单的跨浏览器扩展文本区域的过程中,我发现所有插件的缝隙都过于混乱.
In my attempt to build a simple cross browser expanding text area I found that all plugins seam far too overly cluttered.
我开发了这个:
$(document).ready(function() {
$('textarea').keyup(function() {
var txtheight = this.scrollHeight;
$(this).height(txtheight)
});
$('textarea').keyup();
});
它产生了意外的结果.
在FIREFOX上它可以工作,但是如果我从文本区域删除行,它的大小不会减小.
On FIREFOX it is working but if I delete lines from the textarea it does not reduce in size.
在CHROME上,按任意键会导致添加另一个行高.
On CHROME the presseing of any key leads to another line height being added.
这非常令人困惑,因为如果相反,我将代码更改为此:
This is extremely confusing because if instead I change the code to this:
$(document).ready(function() {
$('textarea').keyup(function() {
var txtheight = this.scrollHeight;
alert(txtheight);
});
$('textarea').keyup();
});
在两个浏览器上,警报每次都会获取正确的数字.到底是怎么回事?
The alert gets the number correct every single time on both Browsers. What the hell is going on?
推荐答案
以下是一种可行的方法:
Here's one approach that seems to work:
$('#test').on('keydown', function(e){
var that = $(this);
if (that.scrollTop()) {
$(this).height(function(i,h){
return h + 20;
});
}
});
以稍微复杂的方式对上述内容进行了修改,但我认为具有适当的准确性:
Amended the above, in a slightly complicated manner but with, I think, proper accuracy:
function heightComparison(el) {
if (!el) {
return false;
}
else {
var $el = $(el),
clone = $('#' + el.id + '-clone'),
cH = clone.height();
$el.height(cH);
}
}
$('#test').on('keyup paste', function(e) {
var that = this,
$that = $(that),
clone = $('#' + that.id + '-clone').length ? $('#' + that.id + '-clone') : $('<div />', {
'id': that.id + '-clone'
}).css({
'position': 'absolute',
'left': '-1000px',
'border-width': '1px',
'border-color': '#000',
'border-style': 'solid',
'overflow': 'hidden',
'width': $that.width(),
'min-height': $that.height(),
'padding': $that.css('padding'),
'font-size': $that.css('font-size'),
'font-family': $that.css('font-family')
}).appendTo('body');
clone.text($that.val());
heightComparison(that);
});
这篇关于简单的jQuery textarea扩展以适合内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!