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

标签 javascript jquery html css

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

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

textarea 的高度是 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 之后而不是之前更新 innerHeighthttp://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);

关于javascript - 为什么在 Chrome 中输入更改时 TEXTAREA 的 scrollHeight 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26633164/

相关文章:

html - 菜单和子菜单之间的 CSS 空间

javascript - jQuery 点击触发禁用移动页面

jquery - 使用 JQuery 从 JSON 或 XML 提要生成 HTML 表单

c# - 如何将 HTML 分配给隐藏代码中的字符串?

javascript - 通过 javascript 将复杂参数传递给 Web API 服务

javascript - 实现点赞功能时出现问题。函数只运行一次

html - 在 Safari 上强制滚动条

javascript - 使 CompareValidator 有条件地验证

javascript - 如果导航到 React Native 中的其他屏幕,如何保留 formik 表单值

javascript - 如何在javascript中将正斜杠替换为反斜杠?