私がしようとしているのは、テキストを入力するかテキストを貼り付けると、Textarea が自動拡張されるようにすることです。IE7、IE8、IE9、Firefox で問題なく動作しています。ただし、OPERA、CHROME、および SAFARI では、Shift、Ctrl、下矢印、上矢印、左矢印、右矢印、Home、End、Delete などの機能キー/追加キーをクリックしても自動成長します。
Jクエリコード:
<script type="text/javascript">
function txtareaAutoGrow(txtar, clkBtn){
// txtareaAutoGrow() start here
$("#"+txtar).height(18);
$("#"+txtar).keyup(function(){
if ($("#"+txtar).height() <= 18){
$(this).height(18);
}
else {
$(this).height($("#"+txtar).prop("scrollHeight"));
$("#"+txtar).bind('paste', function() {
setTimeout(function() {
$("#"+txtar).height($("#"+txtar).prop("scrollHeight"));
}, 100);
});
}
});
$("#"+clkBtn).click(function(){
if ($("#"+txtar).height() <= 18){
$("#"+txtar).height($("#"+txtar).prop("scrollHeight"));
}
else {
$("#"+txtar).height(18);
}
});
// txtareaAutoGrow() end here
};
</script>
HTML コード:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Resize TEXTAREA</title>
<style type="text/css">
textarea {
overflow:hidden;
resize: none;}
</style>
<script type="text/javascript" src="jquery-latest.js"></script>
<script type="text/javascript" src="autoresizeTextarea.js"></script>
<script type="text/javascript">
$(document).ready(function() {
txtareaAutoGrow("txtar1", "btnXpand1");
txtareaAutoGrow("txtar2", "btnXpand2");
});
</script>
</head>
<body>
<p>
<textarea cols="100" id="txtar1"></textarea>
<input type="button" id="btnXpand1" value="Expand/Collapse" />
<p> </p>
<textarea cols="100" id="txtar2"></textarea>
<input type="button" id="btnXpand2" value="Expand/Collapse" />
</p>
<p>
<!--<input type="button" id="Heght" value="Height" />
<input type="button" id="scrlHeight" value="Scroll Height" />
<input type="button" id="btnXpand" value="Expand/Collapse" />-->
</p>
</body>
</html>