最近做项目遇见了这个自适应高度的问题,也在网上找了些资料,大多选择用DIV模拟textarea,但是这样就有安全性的问题,因为你是可以直接将HTML代码输入进去的。
接下来介绍的这种办法是采用两个textarea,其中一个textarea设置其absolute,设置其不可见。当输入文本的textarea的值变化时,将原本的textarea中的值copy到新的 textarea中,这样可以准确计算高度(注意在copy节点的时候新旧textarea的宽度是一样的)。
为什么不直接用原textarea的高度呢,应该是存在延迟的问题吧。至于网上很多直接用文字长度除以宽度从而获得高度的做法只适合于等宽字体,数字标点什么的宽度问题,这样自然会造成很大的误差啊。
这里展示一下textarea中的textchange函数
$scope.TextChange=function(){ var element=document.getElementById("getmessage"); var other=document.getElementById("clonemessage"); if(!other){ other=element.cloneNode(true); other.setAttribute("id","clonemessage"); var parent=element.parentNode; parent.appendChild(other); angular.element(other).css({ "min-height": 0, "height": 0, "visibility": "hidden", "position":"absolute", "width":element.offsetWidth+"px", "top": 0 }) } other.value=element.value; element.style.height=other.scrollHeight+"px"; }
因为这里项目中用的angular框架,所以里面带一下angular元素。需要注意的是在设置宽度和高度时要加单位‘px’,而且在JS中获取元素的宽度和高度用的(元素名).offserWidth,
在设置元素宽度和高度时用的是(元素名).style.height。
这里还有一个JQuery的版本
function autoHeight() { var $other=$(this).parent().find(".autoHeightClone"); if($other.length<=0){ $other=$(this).clone(); $other.addClass("autoHeightClone") .appendTo($(this).parent()); $other.css({ "min-height": 0, "height": 0, "visibility": "hidden", "position":"absolute", "width": $(this).outerWidth(), "top": 0 }); } $other.val(this.value); $(this).innerHeight($other[0].scrollHeight); }