textarea 无边框无滚动条自适应高度的实现

http://blog.csdn.net/junval/archive/2007/08/29/1763541.aspx

代码

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextArea.aspx.cs" Inherits="TextArea" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>textarea 无边框无滚动条自适应高度的实现</title>
    <style type="text/css">...
        .info {...}{
          font-size: 12px;
          overflow:hidden;
          background-color: #ffffcc;
          color: black;
          width:100%;
          line-height:12px;
          padding-right:5px;
          padding-left:5px;
          font-family: courier;
          width:100%;
          letter-spacing:0; 
          border-style:none;
        }
    </style>
    <script language="javascript" type="text/javascript">
    function setRows(obj){
      var textarea = obj;
      var cols = textarea.cols;
      var str = textarea.value;
      str = str.replace(/ ?/, " ");
      var lines =  textarea.rows;
      var chars = 0;
      for (i = 0; i < str.length; i++) {
        var c = str.charAt(i);
        chars++;
        if ( c == " ")
        {
           lines ++;
        }
        else
        {
           if (i > lines * (cols/2) )      //这里是中文模式除2 如果是输入英文字符修改为1 即可
           {
              lines ++;
           }
        }
      }
     textarea.setAttribute("rows", lines);
     textarea.style.height = lines*12 + "px";
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <textarea id='LogC' onkeyup='setRows(this)' class='info' cols='75'rows='12'>可以根据内容自适应调整高度</textarea>
    </div>
    </form>
</body>
</html>

你可能感兴趣的:(textarea)