Textarea 使用 Jquery 根据内容调整大小(使用 form-control class)
Textarea adjust size based on content (with form-control class) using Jquery
大家好,
我想根据 content.For 调整我的文本区域的大小,我试过像
这样的代码
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
<br/>
</div>
</div>
并使用 jquery
function textAreaAdjust(o) {
o.style.height = "1px";
o.style.height = (25+o.scrollHeight)+"px";
}
我面临的问题是即使是退格键,删除任何新闻 textarea 正在扩展,就像 verylong.It 继续工作,就像 textarea 会随着任何键增加 press.If 我试过 textarea 没有 'class="form-control"' 它的工作 fine.But 响应能力不是 well.Please 任何人都可以帮助我提前摆脱这个 issue.Thanks。
您可以检测到按键,如果是退格键,请不要做任何事情,所以您可以试试这个
$('#answer_sample').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code != 8) { //Backspace keycode
$(this).css('height', '1px');
$(this).css('height', 25+o.scrollHeight)+'px');
}
});
并从 HTML 中删除函数
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
<br/>
</div>
</div>
久经考验
$(document).ready(function(){
$("#answer_sample").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea>
<br/>
</div>
</div>
</body>
</html>
使用jquery-elastic插件Link is dead
在此处检查项目的分支 Github Jquery-elastic
使用只需要一行代码..
$('#answer_sample').elastic();
/**
* @name Elastic+
* @descripton grow and shrink your textareas automatically
*
* @author Casey W. Stark
* @author-email casey@thestarkeffect.com
* @author-website http://thestarkeffect.com
*
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* the original by:
* @author Jan Jarfalk
* @author-email jan.jarfalk@unwrongest.com
* @author-website http://www.unwrongest.com
*/
(function($) {
$.fn.elastic = function(options) {
// We will create a div clone of the textarea
// by copying these attributes from the textarea to the div.
var mimics = [
'paddingTop',
'paddingRight',
'paddingBottom',
'paddingLeft',
'fontSize',
'lineHeight',
'fontFamily',
'width',
'fontWeight',
'textIndent'
];
// support multiple elements
if (this.length > 1) {
this.each(function() {
// textareas only
if (this.type != 'textarea') return false;
$this.elastic()
});
return this;
}
// cache the textarea jquery object
var textarea = this;
var twin = $('<div></div>').css({
'position': 'absolute',
'display': 'none',
'word-wrap': 'break-word'
});
var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10);
var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2;
var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE;
var goalHeight = 0;
var i = 0;
// Opera returns max-height of -1 if not set
if (maxHeight < 0) {
maxHeight = Number.MAX_VALUE;
}
// Append the twin to the DOM
// We are going to meassure the height of this, not the textarea.
twin.appendTo(this.parent());
// Copy the essential styles (mimics) from the textarea to the twin
var i = mimics.length;
while (i--) {
twin.css(mimics[i].toString(), textarea.css(mimics[i].toString()));
}
// Sets a given height and overflow state on the textarea
function setHeightAndOverflow(height, overflow) {
curratedHeight = Math.floor(parseInt(height, 10));
if (textarea.height() != curratedHeight) {
textarea.css({
'height': curratedHeight + 'px',
'overflow': overflow
});
}
}
// This function will update the height of the textarea if necessary
this.resize = function(options) {
// need to update the lineheight if not set
if (!lineHeight) {
lineHeight = parseInt(textarea.css('line-height'), 10);
}
// set width to get proper height (width could change)
twin.width(textarea.width());
// Get curated content from the textarea.
var textareaContent = textarea.val().replace(/&/g, '&').replace(/ /g, ' ').replace(/<|>/g, '>').replace(/\n/g, '<br />');
var twinContent = twin.html();
if (textareaContent + ' ' != twinContent) {
// Add an extra white space so new rows are added when you are at the end of a row.
twin.html(textareaContent + ' ');
// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
if (Math.abs(twin.height() - textarea.height()) > 3) {
var goalHeight = twin.height();
if (goalHeight >= maxHeight) {
setHeightAndOverflow(maxHeight, 'auto');
} else if (goalHeight <= minHeight) {
setHeightAndOverflow(minHeight, 'hidden');
} else {
setHeightAndOverflow(goalHeight, 'hidden');
}
}
}
return textarea;
};
// Hide scrollbars
textarea.css({
'overflow': 'hidden'
});
// Update textarea size on keyup
textarea.keyup(function() {
textarea.resize();
});
// And this line is to catch the browser paste event
textarea.on('input paste', function(e) {
setTimeout(textarea.resize, 250);
});
// Run resize once when elastic is initialized and return the textarea for chaining
return this.resize();
};
})(jQuery);
$('#answer_sample').elastic();
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
Duis autem vel eum iriure dolor in hendrerit in vulputate velit es
</textarea>
<br/>
</div>
</div>
大家好,
我想根据 content.For 调整我的文本区域的大小,我试过像
这样的代码<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
<br/>
</div>
</div>
并使用 jquery
function textAreaAdjust(o) {
o.style.height = "1px";
o.style.height = (25+o.scrollHeight)+"px";
}
我面临的问题是即使是退格键,删除任何新闻 textarea 正在扩展,就像 verylong.It 继续工作,就像 textarea 会随着任何键增加 press.If 我试过 textarea 没有 'class="form-control"' 它的工作 fine.But 响应能力不是 well.Please 任何人都可以帮助我提前摆脱这个 issue.Thanks。
您可以检测到按键,如果是退格键,请不要做任何事情,所以您可以试试这个
$('#answer_sample').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code != 8) { //Backspace keycode
$(this).css('height', '1px');
$(this).css('height', 25+o.scrollHeight)+'px');
}
});
并从 HTML 中删除函数
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
<br/>
</div>
</div>
久经考验
$(document).ready(function(){
$("#answer_sample").keyup(function(e) {
while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
$(this).height($(this).height()+1);
};
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Sample Answer</label>
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea>
<br/>
</div>
</div>
</body>
</html>
使用jquery-elastic插件Link is dead
在此处检查项目的分支 Github Jquery-elastic
使用只需要一行代码..
$('#answer_sample').elastic();
/**
* @name Elastic+
* @descripton grow and shrink your textareas automatically
*
* @author Casey W. Stark
* @author-email casey@thestarkeffect.com
* @author-website http://thestarkeffect.com
*
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* the original by:
* @author Jan Jarfalk
* @author-email jan.jarfalk@unwrongest.com
* @author-website http://www.unwrongest.com
*/
(function($) {
$.fn.elastic = function(options) {
// We will create a div clone of the textarea
// by copying these attributes from the textarea to the div.
var mimics = [
'paddingTop',
'paddingRight',
'paddingBottom',
'paddingLeft',
'fontSize',
'lineHeight',
'fontFamily',
'width',
'fontWeight',
'textIndent'
];
// support multiple elements
if (this.length > 1) {
this.each(function() {
// textareas only
if (this.type != 'textarea') return false;
$this.elastic()
});
return this;
}
// cache the textarea jquery object
var textarea = this;
var twin = $('<div></div>').css({
'position': 'absolute',
'display': 'none',
'word-wrap': 'break-word'
});
var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10);
var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2;
var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE;
var goalHeight = 0;
var i = 0;
// Opera returns max-height of -1 if not set
if (maxHeight < 0) {
maxHeight = Number.MAX_VALUE;
}
// Append the twin to the DOM
// We are going to meassure the height of this, not the textarea.
twin.appendTo(this.parent());
// Copy the essential styles (mimics) from the textarea to the twin
var i = mimics.length;
while (i--) {
twin.css(mimics[i].toString(), textarea.css(mimics[i].toString()));
}
// Sets a given height and overflow state on the textarea
function setHeightAndOverflow(height, overflow) {
curratedHeight = Math.floor(parseInt(height, 10));
if (textarea.height() != curratedHeight) {
textarea.css({
'height': curratedHeight + 'px',
'overflow': overflow
});
}
}
// This function will update the height of the textarea if necessary
this.resize = function(options) {
// need to update the lineheight if not set
if (!lineHeight) {
lineHeight = parseInt(textarea.css('line-height'), 10);
}
// set width to get proper height (width could change)
twin.width(textarea.width());
// Get curated content from the textarea.
var textareaContent = textarea.val().replace(/&/g, '&').replace(/ /g, ' ').replace(/<|>/g, '>').replace(/\n/g, '<br />');
var twinContent = twin.html();
if (textareaContent + ' ' != twinContent) {
// Add an extra white space so new rows are added when you are at the end of a row.
twin.html(textareaContent + ' ');
// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
if (Math.abs(twin.height() - textarea.height()) > 3) {
var goalHeight = twin.height();
if (goalHeight >= maxHeight) {
setHeightAndOverflow(maxHeight, 'auto');
} else if (goalHeight <= minHeight) {
setHeightAndOverflow(minHeight, 'hidden');
} else {
setHeightAndOverflow(goalHeight, 'hidden');
}
}
}
return textarea;
};
// Hide scrollbars
textarea.css({
'overflow': 'hidden'
});
// Update textarea size on keyup
textarea.keyup(function() {
textarea.resize();
});
// And this line is to catch the browser paste event
textarea.on('input paste', function(e) {
setTimeout(textarea.resize, 250);
});
// Run resize once when elastic is initialized and return the textarea for chaining
return this.resize();
};
})(jQuery);
$('#answer_sample').elastic();
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="answer_sample" id="answer_sample" rows="5">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
Duis autem vel eum iriure dolor in hendrerit in vulputate velit es
</textarea>
<br/>
</div>
</div>