zoukankan      html  css  js  c++  java
  • textarea自适应高度

    最近做项目遇见了这个自适应高度的问题,也在网上找了些资料,大多选择用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);
        }
  • 相关阅读:
    poj 3252 Round Numbers 数位DP
    HDU5840 Problem This world need more Zhu 分块 树剖
    有向图强连通分量
    CodeForces
    Gym-100814K 数位DP 模拟除法
    洛谷P3455 [POI2007]ZAP-Queries
    洛谷P2257 YY的GCD
    洛谷P3327 [SDOI2015]约数个数和(莫比乌斯反演)
    莫比乌斯反演
    小知识点
  • 原文地址:https://www.cnblogs.com/pengshuo/p/5747461.html
Copyright © 2011-2022 走看看