늘어나는 Textarea


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <div class="expandingArea">
  2. <pre><span></span><br></pre>
  3. <textarea></textarea>
  4. </div>
  5.  
  6. <style type="text/css">
  7. textarea,
  8. pre {
  9. margin: 0;
  10. padding: 0;
  11. outline: 0;
  12. border: 0;
  13. }
  14.  
  15. .expandingArea {
  16. position: relative;
  17. border: 1px solid #888;
  18. background: #fff;
  19. }
  20.  
  21. .expandingArea > textarea,
  22. .expandingArea > pre {
  23. padding: 5px;
  24. background: transparent;
  25. font: 400 13px/16px helvetica, arial, sans-serif;
  26. /* Make the text soft-wrap */
  27. white-space: pre-wrap;
  28. word-wrap: break-word;
  29. }
  30. .expandingArea > textarea {
  31. /* The border-box box model is used to allow
  32. * padding whilst still keeping the overall width
  33. * at exactly that of the containing element.
  34. */
  35. -webkit-box-sizing: border-box;
  36. -moz-box-sizing: border-box;
  37. -ms-box-sizing: border-box;
  38. box-sizing: border-box;
  39. width: 100%;
  40. /* This height is used when JS is disabled */
  41. height: 100px;
  42. }
  43. .expandingArea.active > textarea {
  44. /* Hide any scrollbars */
  45. overflow: hidden;
  46. position: absolute;
  47. top: 0;
  48. left: 0;
  49. height: 100%;
  50. /* Remove WebKit user-resize widget */
  51. resize: none;
  52. }
  53. .expandingArea > pre {
  54. display: none;
  55. }
  56. .expandingArea.active > pre {
  57. display: block;
  58. /* Hide the text; just using it for sizing */
  59. visibility: hidden;
  60. }
  61. </style>
  62.  
  63. <script type="text/javascript">
  64. function makeExpandingArea(container) {
  65. var area = container.querySelector('textarea');
  66. var span = container.querySelector('span');
  67. if (area.addEventListener) {
  68. area.addEventListener('input', function() {
  69. span.textContent = area.value;
  70. }, false);
  71. span.textContent = area.value;
  72. } else if (area.attachEvent) {
  73. // IE8 compatibility
  74. area.attachEvent('onpropertychange', function() {
  75. span.innerText = area.value;
  76. });
  77. span.innerText = area.value;
  78. }
  79. // Enable extra CSS
  80. container.className += ' active';
  81. }
  82.  
  83. var areas = document.querySelectorAll('.expandingArea');
  84. var l = areas.length;
  85.  
  86. while (l--) {
  87. makeExpandingArea(areas[l]);
  88. }
  89. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.