js textarea 自适应高度
程序员文章站
2022-06-13 08:24:50
...
写道
<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
border: 0 none white;
overflow: hidden;
padding: 0;
outline: none;
background-color: white;
resize: none;
}
</style>
</head>
<body onload="init();">
<textarea cols="8" rows="1" style="height:25px;" id="text">1234567890123456789</textarea>
</body>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
//text.focus();
//text.select();
resize();
</script>
</html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
border: 0 none white;
overflow: hidden;
padding: 0;
outline: none;
background-color: white;
resize: none;
}
</style>
</head>
<body onload="init();">
<textarea cols="8" rows="1" style="height:25px;" id="text">1234567890123456789</textarea>
</body>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
//text.focus();
//text.select();
resize();
</script>
</html>