textarea高度自增代码教程
程序员文章站
2022-04-23 19:33:18
textarea高度自增代码教程
var observe;
if (window.attachEvent) {
observe = function (e...
textarea高度自增代码教程
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); }; } function init () { var text = document.getElementById('text');//textarea元素 var textBox = document.getElementById('textBox');//textarea父级元素 可有可无 function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+7+'px'; textBox.style.height = text.scrollHeight+26+'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(); } init()
通过获取textarea的scrollHeight来实现高度自增,类似微信的输入框。