为什么在Chrome中输入更改时,TEXTAREA的scrollHeight错误

Why do I get wrong scrollHeight for TEXTAREA on input change in Chrome?

本文关键字:TEXTAREA scrollHeight 错误 Chrome 输入 为什么      更新时间:2023-09-26

我正在尝试编写一个JavaScript来自动调整文本区域的文本大小。

我的问题是:在行被填充后,scrollHeight在每一秒符号上都返回错误的值(您可以在控制台中看到日志输出)。

文本区域的高度是47,我交替得到62和47(没有调整大小)。

JQuery插件:

; (function($) {
/**
 * Resizes the text in the textarea
 * @version 0.1
 */
$.fn.textResizer = function(options) {
    options = jQuery.extend({
        maxFontSize: null,
        minFontSize: 8,
        step: 1
    }, options);
    return this.each(function() {
        var maxHeight = $(this).outerHeight();
        $(this).bind('input propertychange', function() {
            var innerElements = $(this).children(':visible');
            console.log($(innerElements));
            var fontSize = options.maxFontSize,
                innerHeight;
            console.log('inner: '+$(this).css( "height" )+ ', max: '+maxHeight, 'outer: '+$(this).outerHeight());
            console.log(this.scrollHeight);
            do {
                innerHeight = this.scrollHeight;
                console.log(this.scrollHeight);
                fontSize = fontSize - options.step;
                $(this).css('font-size', fontSize);
            } while ((innerHeight > maxHeight) && fontSize > options.minFontSize);
        });
    });
};
})(jQuery);

CSS:

textarea {
    position: absolute;
    width:176px;
    height:47px;
    top: 4px;
    left: 60px;
    background: #666666;
    border: none;
    color: #fff;
    overflow: hidden;
    display:inline-block;
    vertical-align: middle;
    resize: none;
    padding: 0;
  }

HTML:

<script>
$(document).ready(function() {
    $('textarea').textResizer({'maxFontSize':30});
});
</script>
<textarea></textarea>

下面是我的例子:http://jsfiddle.net/6nhLmcge/

这种行为的原因是什么?

你知道这个任务的其他解决方案/插件吗?

您需要在更改css之后而不是之前更新innerHeight。http://jsfiddle.net/svt8zsx4/

           do {
               //innerHeight = $(this).innerHeight();
                console.log(this.scrollHeight);
                fontSize = fontSize - options.step;
                $(this).css('font-size', fontSize);
                innerHeight = this.scrollHeight;
            } while ((innerHeight > maxHeight) && fontSize > options.minFontSize);