我有一个非常好的小功能,当某些 div 开始溢出时,当它们显示在屏幕上时,可以减小它们内部的文本大小。
$(function(){
$('div.Body').each(function (index) {
if ($('div.Body')[index].scrollHeight > 150) {
$('div.Body')[index].style.fontSize = 'small';
if ($('div.Body')[index].scrollHeight > 150) {
$('div.Body')[index].style.fontSize = 'x-small';
if ($('div.Body')[index].scrollHeight > 150) {
$('div.Body')[index].style.fontSize = 'xx-small';
}
}
}
});
})
当用户在提交文本时将文本输入到textArea时,我想使用相同/相似的函数来执行相同的操作,但是textArea似乎没有scrollHeight的函数:
$(function() {
window.status = $('.TextAreaClass').scrollHeight;
});
此函数仅返回未定义。
如何在文本区域中完成此操作?
最佳答案
只需使用 this
,而不是为循环的每次迭代获取 $('div.Body')[index]
:
$('div.Body').each(function () { // Remove the redundant parameter
if (this.scrollHeight > 150) {
this.style.fontSize = 'small';
if (this.scrollHeight > 150) {
this.style.fontSize = 'x-small';
if (this.scrollHeight > 150) {
this.style.fontSize = 'xx-small';
}
}
}
});
在.each
中,this
引用$('div.Body')[index]
。
并且,正如 Rory 所说,$('.TextAreaClass')
返回一个 jQuery 对象。您可能需要使用 $('.TextAreaClass')[0];
访问该对象中的第一个 DOM 元素。
关于javascript - 使用 jQuery 键入时减小 TextArea 中文本的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14193728/