如何自动增长具有可变字体大小的文本框

时间:2018-07-10 10:17:04

标签: javascript jquery css

我正在编写一个网站,供您测试字体,就像Google字体一样,当用户输入更多文本时,您键入的文本区域应自动增长。

我通过jaz303尝试了此插件,如果字体大小保持不变,它可以正常工作。 https://github.com/jaz303/jquery-grab-bag/blob/master/javascripts/jquery.autogrow-textarea.js

  (function($) {
/**
 * Auto-growing textareas; technique ripped from Facebook
 *
 *
 * http://github.com/jaz303/jquery-grab-bag/tree/master/javascripts/jquery.autogrow-textarea.js
 */
$.fn.autogrow = function(options) {
  return this.filter('textarea').each(function() {
    var self = this;
    var $self = $(self);
    var minHeight = $self.height();
    var noFlickerPad = $self.hasClass('autogrow-short') ? 0 : parseInt($self.css('lineHeight')) || 0;
    var settings = $.extend({
      preGrowCallback: null,
      postGrowCallback: null
    }, options);

    var shadow = $('<div></div>').css({
      position: 'absolute',
      top: -10000,
      left: -10000,
      width: $self.width(),
      fontSize: $self.css('fontSize'),
      fontFamily: $self.css('fontFamily'),
      fontWeight: $self.css('fontWeight'),
      lineHeight: $self.css('lineHeight'),
      resize: 'none',
      'word-wrap': 'break-word'
    }).appendTo(document.body);

    var update = function(event) {
      var times = function(string, number) {
        for (var i = 0, r = ''; i < number; i++) r += string;
        return r;
      };

      var val = self.value.replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\n$/, '<br/>&#xa0;')
        .replace(/\n/g, '<br/>')
        .replace(/ {2,}/g, function(space) {
          return times('&#xa0;', space.length - 1) + ' '
        });

      // Did enter get pressed?  Resize in this keydown event so that the flicker doesn't occur.
      if (event && event.data && event.data.event === 'keydown' && event.keyCode === 13) {
        val += '<br />';
      }

      shadow.css('width', $self.width());
      shadow.html(val + (noFlickerPad === 0 ? '...' : '')); // Append '...' to resize pre-emptively.

      var newHeight = Math.max(shadow.height() + noFlickerPad, minHeight);
      if (settings.preGrowCallback != null) {
        newHeight = settings.preGrowCallback($self, shadow, newHeight, minHeight);
      }

      $self.height(newHeight);

      if (settings.postGrowCallback != null) {
        settings.postGrowCallback($self);
      }
    }

    $self.change(update).keyup(update).keydown({
      event: 'keydown'
    }, update);
    $(window).resize(update);

    update();
  });
};

但是,我需要用户在测试时更改字体大小,并且由于某种原因,一旦更改大小,自动增长功能将不再起作用。

这是我的Test jsFiddle: http://jsfiddle.net/fquk6v3o/2/

2 个答案:

答案 0 :(得分:1)

解决方案是在滑块值更改时重新启动$("#autoGrowTextArea").autogrow(); ...

执行此操作的示例代码:

$("input[type='range']").change( function() { 
  $("#autoGrowTextArea").height("100px");
  $("#autoGrowTextArea").autogrow();
});

此处有新的JSfiddle:http://jsfiddle.net/newzy08/fquk6v3o/3/

答案 1 :(得分:0)

您也可以使用CSS以em单位的高度和宽度来实现此目的。 Em表示相对于元素的字体大小(2em表示当前字体大小的2倍)w3schools.com/cssref/css_units.asp

我不知道这是否可以与autogrowth插件一起很好地工作。

$(document).ready(function(){
    $("#font-small").click(function(){
        $(".ta").css("font-size", "12px");
    });
    $("#font-big").click(function(){
        $(".ta").css("font-size", "24px");
    });
    $("#font-huge").click(function(){
        $(".ta").css("font-size", "36px");
    });
});
.ta {
  font-size: 12px;
  height: 3em;
  width: 10em;
  resize: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <textarea class="ta">test</textarea>
</div>
<div>
    <button id="font-small">fontsmall</button>
    <button id="font-big">fontbig</button>
    <button id="font-huge">fonthuge</button>
</div>