棘手的部分是减少字体大小的算法。这里有两个解决方案。
first one 是你见过的最丑陋的代码(抱歉这里是凌晨 4:30,我累了)但它展示了解决方案,递归函数
$(document).ready(function() {
var textAreaHeight = $('#inp').height();
var fontSize = 200;
var font = fontSize + "px";
$('#inp').css("font-size", font);
$('.hidden').css("font-size", font);
$('#inp').keyup(function() {
var txt = $(this).val();
$('#hiddenSpan').html(txt);
fontSize = decreaseFontSize(fontSize);
font = fontSize + 'px';
$('#inp').css("font-size", fontSize + 'px');
})
function decreaseFontSize(tempFontSize) {
var textHeight = $('#hiddenSpan').height();
if (textHeight > textAreaHeight) {
var factor = .99; /* Arbitrary scaling factor */
tempFontSize *= factor;
$('#hiddenSpan').css("font-size", tempFontSize + 'px');
return decreaseFontSize(tempFontSize);
} else {
return tempFontSize;
}
}
})
second one 更简洁,但只要您到达末尾,只需添加另一行。
$(document).ready(function() {
var textAreaHeight = $('#inp').height();
var fontSize = 200;
var inputLength = 0;
var font = fontSize + "px"
$('#inp').css("font-size", font);
$('.hidden').css("font-size", font);
$('#inp').keyup(function() {
var txt = $(this).val();
$('#hiddenSpan').html(txt);
var textHeight = $('#hiddenSpan').height();
if( textHeight > textAreaHeight ) {
var font = decreaseFontSize( textHeight) + "px";
$(this).css("font-size", font);
$('.hidden').css("font-size", font);
}
})
function decreaseFontSize( textHeight) {
fontSize = textAreaHeight/(textHeight/fontSize); /* textHeight / fontSize will tell you how many rows are currently in the #hiddenSpan and will then fit those rows inside the height of the textArea */
return fontSize;
}
})
实际上,使这两种解决方案都起作用的答案的主要部分是我将其添加到您的#hiddenSpan
#hiddenSpan {
max-width: 300px; /* Makes the text wrap like the input box */
display: inline-block;
word-wrap: break-word; /* Paired with display, allows the text to wrap */
font-family: "Times New Roman", Times, serif; /* Added the same font to both elements so that they could actually be coordinated */
}
在用我的小手指能收集到的尽可能多的字符测试这两个之后,我注意到递归函数稍微好一点,但没有你想象的那么多。