Нет описания

adjustHeight.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //textarea根据文本域内容自动调整高度
  2. //用法在textarea中直接添加data-adaptheight属性即可
  3. (function() {
  4. function adjustHeight(textareaElement, minHeight) {
  5. // compute the height difference which is caused by border and outline
  6. // 计算因边框和轮廓产生的高度差异
  7. var outerHeight = parseInt(window.getComputedStyle(el).height, 10);
  8. var diff = outerHeight - el.clientHeight;
  9. // set the height to 0 in case of it has to be shrinked
  10. // 设置高度为0以防需要收缩(高度)
  11. el.style.height = 0;
  12. // set the correct height
  13. // el.scrollHeight is the full height of the content, not just the visible part
  14. // 设置正确的高度
  15. // el.scrollHeight 是文本内容的全部高度,而不仅仅是可见部分的。
  16. el.style.height = Math.max(minHeight, el.scrollHeight + diff) + 'px';
  17. }
  18. // we use the "data-adaptheight" attribute as a marker
  19. // 我们使用"data-adaptheight"属性作为一个标记
  20. var textAreas = document.querySelectorAll('textarea[data-adaptheight]');
  21. // iterate through all the textareas on the page
  22. // 迭代本页所有的文本域
  23. for (var i = 0, l = textAreas.length; i < l; i++) {
  24. var el = textAreas[i];
  25. // we need box-sizing: border-box, if the textarea has padding
  26. // 如果文本域有边距,我们需要设置box-sizing: border-box
  27. el.style.boxSizing = el.style.mozBoxSizing = 'border-box';
  28. // we don't need any scrollbars, do we? :)
  29. // 我们不需要滚动条,不是么? :)
  30. //el.style.overflowY = 'hidden';
  31. // the minimum height initiated through the "rows" attribute
  32. // 通过"rows"属性初始化的最小高度
  33. var minHeight = el.scrollHeight;
  34. el.addEventListener('input', function() {
  35. adjustHeight(el, minHeight);
  36. });
  37. // we have to readjust when window size changes (e.g. orientation change)
  38. // 当窗口大小改变时,我们需要重新调整高度(例如方向变化)
  39. window.addEventListener('resize', function() {
  40. adjustHeight(el, minHeight);
  41. });
  42. // we adjust height to the initial content
  43. // 我们调整初始内容的高度
  44. adjustHeight(el, minHeight);
  45. }
  46. }());