码迷,mamicode.com
首页 > 其他好文 > 详细

textarea自适应高度

时间:2016-08-07 23:18:10      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

最近做项目遇见了这个自适应高度的问题,也在网上找了些资料,大多选择用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);
    }

 

textarea自适应高度

标签:

原文地址:http://www.cnblogs.com/pengshuo/p/5747461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!