2009-11-28 120 views
5

有沒有一種簡單的方法可以使填充高度達到頁面的高度?使TextArea垂直填充頁面的其餘部分?

+0

[notepad.cc](http://notepad.cc/)演示了這種效果 - 你可以嘗試弄清楚它們是如何做到的。他們的方法在調整窗口大小時調整textarea的大小,甚至在禁用JavaScript的情況下也能正常工作。我不確定它是否依賴於知道textarea上方和下方內容的高度。 – 2012-09-05 17:57:19

回答

4

我認爲設置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

相關問題