使TextArea垂直填充页面的其余部分?

问题描述:

有没有一种简单的方法可以使填充高度达到页面的高度?使TextArea垂直填充页面的其余部分?

+0

[notepad.cc](http://notepad.cc/)演示了这种效果 - 你可以尝试弄清楚它们是如何做到的。他们的方法在调整窗口大小时调整textarea的大小,甚至在禁用JavaScript的情况下也能正常工作。我不确定它是否依赖于知道textarea上方和下方内容的高度。 – 2012-09-05 17:57:19

我认为设置height: 100%对于textarea只能在IE中工作,如果你明确地将它设置为怪癖模式,尽管它在Firefox中按预期工作是很重要的。 W3C指出textarea的大小是用行而不是像素等来定义的。

下面显示的是确保文本区总是占用整个身高的一种简单方法,考虑到用户安装的工具栏等,不同的显示器分辨率,甚至可能调整大小的窗口。关键是简单的JS方法和它的位置。表单就在那里模拟正常的文本框和标签。

<html> 
    <head runat="server"><title>Look, Mom! No Scrollbars!</title></head> 
    <body onload="resizeTextArea()" onresize="resizeTextArea()"> 
     <form id="form1" runat="server"> 
      <div id="formWrapper" style="height:200px"> 
       <input type="text" value="test" /> 
       <input type="text" value="test" /> 
      </div> 
      <textarea id="area" style="width: 100%"></textarea> 
     </form> 

     <script type="text/javascript"> 
      function resizeTextArea() { 
       //Wrap your form contents in a div and get its offset height 
       var heightOfForm = document.getElementById('formWrapper').offsetHeight; 
       //Get height of body (accounting for user-installed toolbars) 
       var heightOfBody = document.body.clientHeight; 
       var buffer = 35; //Accounts for misc. padding, etc. 
       //Set the height of the textarea dynamically 
       document.getElementById('area').style.height = 
        (heightOfBody - heightOfForm) - buffer; 
       //NOTE: For extra panache, add onresize="resizeTextArea()" to the body 
      } 
     </script> 
    </body> 
</html> 

将其复制并粘贴到新页面。它适用于FF和IE。

希望这会有所帮助!

+0

这里是[textarea'元素的W3C规范](http://www.w3.org/TR/html5/the-textarea-element.html#the-textarea-element)。我不知道它在哪里说textarea的大小是以行*而不是*像素定义的,所以我不明白你的意思。是的,它起始于行数的高度,这要归功于'rows'属性,但在此之后,你可以给它任何你想要的高度,例如,用CSS'#area {height:100px; }'。 – 2012-09-05 17:29:18

+0

[这个答案的JS斌](http://jsbin.com/ugosup/1/edit)。在Firefox和Chrome中,它在[代码视图](http://jsbin.com/ugosup/1/edit)中适用于我,但在[整页视图](http://jsbin.com/ ugosup/1)。 – 2012-09-05 17:41:25