Javascript 實現(xiàn) Textarea 自動伸縮的幾種方法:
XML/XHTML 代碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www./TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Javascript 實現(xiàn) Textarea 自動伸縮,兼容IE6、IE7、IE8、IE9、Firefox、Safari、Chome、Opera</title>
<style type="text/css">
textarea{padding-top:0;padding-bottom:0;overflow: hidden;}
</style>
</head>
<body>
<table>
<tr valign="top">
<td>方法1:支持拷貝粘貼、刪除操作<br /><textarea id="textarea1" onkeyup="AutoExpand(this)" onfocus="AutoExpand(this)"></textarea></td>
<td>方法2:只支持輸入<br /><textarea id="textarea"></textarea></td>
<td>方法3:只支持輸入<br /><textarea onpropertychange="MaxMe(this)" oninput="MaxMe(this)" ontextinput="MaxMe(this)"></textarea></td>
</tr>
</table>
<script type="text/javascript">
var InitHeight = 20;
function AutoExpand(e) {
var HideTextarea = document.getElementById("__hidetextarea");
if (!HideTextarea) {
HideTextarea = document.createElement("textarea");
HideTextarea.id = "__hidetextarea";
HideTextarea.style.borderWidth = 0;
document.body.appendChild(HideTextarea);
}
HideTextarea.value = e.value;
HideTextarea.style.height = "0px";
HideTextarea.style.overflow = "hidden";
var x = HideTextarea.scrollHeight + "必須先計算下scrollHeight的值,否則,scrollHeight 的值將固定?";
delete x;
e.style.height = Math.max(Math.max(InitHeight,20), HideTextarea.scrollHeight) + "px";
}
function MaxMe(o) {
if (window.navigator.userAgent.indexOf("Firefox") > -1) {
o.style.height = o.scrollTop + o.scrollHeight + "px";
}
else {
if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px";
}
}
function Init() {
var t1 = document.getElementById("textarea1");
InitHeight = t1.offsetHeight;
var textarea = document.getElementById("textarea");
if (textarea.addEventListener) { // 非Internet Explorer和Internet Explorer9之后的版本
textarea.addEventListener("input", OnTextInput, false);
// Google Chrome 和 Safari
textarea.addEventListener("textinput", OnTextInput, false);
}
if (textarea.attachEvent) { // Internet Explorer 和 Opera
textarea.attachEvent("onpropertychange", OnTextInput);
}
}
function OnTextInput(evt) {
o = window.event ? window.event.srcElement : evt.target;
if (window.navigator.userAgent.indexOf("Firefox") > -1) {
o.style.height = o.scrollTop + o.scrollHeight + "px";
}
else {
if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px";
}
}
window.onload = Init;
</script>
</body>
</html>