运行此代码段时,您将看到以下内容(至少在Chrome 97.0.4692.71中如此):
clientHeight
和scrollHeight
比1行所需的要多。line-height
是undefined
。设置line-height
会影响初始clientHeight
和scrollHeight
值。clientHeight
或scrollHeight
。它们似乎有足够的空间来初始化2行。scrollHeight
,但它并不等于textHeight
。scrollHeight
增加,但是没有添加到文本中的换行符(也就是说,textHeight
不会改变)。用来得出观察到的clientHeight
和scrollHeight
值的计算是什么?
const textarea = document.querySelector('textarea');
document.addEventListener('DOMContentLoaded', () => {
resize(textarea);
});
textarea.addEventListener('input', (inputEvent) => {
resize(inputEvent.target);
});
function resize(o) {
const lines = getLines(o);
const fontSize = getCSSIntegerValue(o, 'font-size');
const padding = getCSSIntegerValue(o, 'padding');
const borderWidth = getCSSIntegerValue(o, 'border-width');
const textHeight = fontSize * lines;
console.log('fontSize=%d, lines=%d, padding=%d, borderWidth=%d, textHeight=%d, clientHeight=%d, scrollHeight=%d', fontSize, lines, padding, borderWidth, textHeight, o.clientHeight, o.scrollHeight);
}
function getCSSIntegerValue(o, property) {
const computedValues = window.getComputedStyle(o);
const propertyValue = computedValues.getPropertyValue(property);
return parseInt(propertyValue.replace(/\D/g, ''));
}
function getLines(o) {
const lines = o.value.split(/\r|\r\n|\n/);
return lines.length;
}
textarea {
all: unset;
background-color: #ddd;
overflow-y: hidden;
overflow-x: hidden;
overflow-wrap: break-word;
font-size: medium;
}
<textarea></textarea>
发布于 2022-01-17 02:29:39
除非定义,否则line-height
将使用用户代理样式表(根据MDN,桌面浏览器通常使用1.2 )。有了这些信息,结果应该更有意义。
clientHeight
总是2 * line-height
。
scrollHeight
是line-height * lines
。
https://stackoverflow.com/questions/70735796
复制相似问题