gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:23 24 4
gpt4 key购买 nike

我正在尝试编写一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com