我创建了一个jQuery弹性插件。我遇到的问题是,如果我在第一行写了一个单词(如“jQuery”),然后按Enter键,则“jQuery”单词将隐藏几毫秒,然后将新行插入textarea 。jQuery弹性textarea插件
我的插件页面 - http://jsfiddle.net/yash_wow/7F8aK/3/
请帮我解决这个问题。
P.S. - 我不想使用任何其他插件,我不希望代码在textarea的底部插入额外的行,就像所有其他弹性插件一样!
我创建了一个jQuery弹性插件。我遇到的问题是,如果我在第一行写了一个单词(如“jQuery”),然后按Enter键,则“jQuery”单词将隐藏几毫秒,然后将新行插入textarea 。jQuery弹性textarea插件
我的插件页面 - http://jsfiddle.net/yash_wow/7F8aK/3/
请帮我解决这个问题。
P.S. - 我不想使用任何其他插件,我不希望代码在textarea的底部插入额外的行,就像所有其他弹性插件一样!
我确实设法调整了您的插件在Chrome here(未在其他浏览器上测试过)中工作。本质上,我必须以特殊的方式处理Enter,以避免将新行添加到文本框的底部,并向下滚动以自动查看,然后您有机会生成文本框。
我还不得不添加.keyup()
,以便退格工作。
下面是完整的JavaScript:
/*
Author - Yash Mathur
*/
jQuery.fn.autoGrow = function() {
return this.each(function() {
var colsDefault = this.cols;
var rowsDefault = this.rows;
var grow = function() {
growByRef(this);
}
var growByRef = function(obj, enterPressed) {
var linesCount = 0;
var lines = obj.value.split('\n');
for (var i = lines.length - 1; i >= 0; --i) {
linesCount += Math.floor((lines[i].length/colsDefault) + 1);
}
if (enterPressed) linesCount++;
if (linesCount > rowsDefault) obj.rows = linesCount;
else obj.rows = rowsDefault;
}
var characterWidth = function(obj) {
var characterWidth = 0;
var temp1 = 0;
var temp2 = 0;
var tempCols = obj.cols;
obj.cols = 1;
temp1 = obj.offsetWidth;
obj.cols = 2;
temp2 = obj.offsetWidth;
characterWidth = temp2 - temp1;
obj.cols = tempCols;
return characterWidth;
}
$(this).keypress(function(evt) {
if (evt.which == 13) {
growByRef(this, true);
this.value += '\n';
return false;
} else {
growByRef(this, false);
}
});
$(this).keyup(function(evt) {
if (evt.which == 13)
return false;
growByRef(this, false);
});
this.style.overflow = "hidden";
//this.onkeyup = grow;
this.onfocus = grow;
this.onblur = grow;
growByRef(this);
});
};
$("textarea").autoGrow();
抱歉“超晚评论”!但感谢一个TONNNNN! :d – user1025469
/*
Author - Yash Mathur
*/
jQuery.fn.autoGrow = function(){
return this.each(function(){
var colsDefault = this.cols;
var rowsDefault = this.rows;
var grow = function() {
growByRef(this);
}
var growByRef = function(obj) {
var linesCount = 0;
var lines = obj.value.split('\n');
for (var i=lines.length-1; i>=0; --i)
{
linesCount += Math.floor((lines[i].length/colsDefault) + 1);
}
if (linesCount > rowsDefault)
obj.rows = linesCount;
else
obj.rows = rowsDefault;
}
var characterWidth = function (obj){
var characterWidth = 0;
var temp1 = 0;
var temp2 = 0;
var tempCols = obj.cols;
obj.cols = 1;
temp1 = obj.offsetWidth;
obj.cols = 2;
temp2 = obj.offsetWidth;
characterWidth = temp2 - temp1;
obj.cols = tempCols;
return characterWidth;
}
this.style.overflow = "hidden";
this.onkeydown = grow;
this.onfocus = grow;
this.onblur = grow;
this.keypress = grow;
growByRef(this);
});
};
$("textarea").autoGrow();
你不觉得按键响应和的keydown要好得多。
我看不到问题。你正在使用哪种浏览器? – rmorero
即时通讯谷歌浏览器v 15.0.874.106 – user1025469
确定其在Firefox中工作正常 但为什么它不在谷歌浏览器中工作? – user1025469