在某些网站(例如 Github)上,文本区域有一组min-height
and max-height
。当用户输入内容时,它们会随着内容而增长,直到达到最大高度。然后出现垂直滚动条。
这种效果是如何实现的呢?我的文本区域不会随着其内容而增长,即使它尚未达到指定的值max-height
textarea{
width:100%;
min-height:80px;
max-height:200px;
overflow:auto;
}
看看这个演示 https://codepen.io/anon/pen/qqMjaP
看看这个Pen https://codepen.io/anon/pen/gLdRXE.
JS
这个片段可以解决这个问题:
var textarea = document.querySelector('textarea');
textarea.addEventListener('keydown', autosize);
function autosize(){
var el = this;
setTimeout(function(){
el.style.cssText = 'height:auto; padding:0';
// for box-sizing other than "content-box" use:
// el.style.cssText = '-moz-box-sizing:content-box';
el.style.cssText = 'height:' + el.scrollHeight + 'px';
},0);
}
CSS
我将其添加到 css 中,使其只能垂直调整大小:
resize:vertical;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)