首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >textarea的scrollHeight和clientHeight是如何计算的?

textarea的scrollHeight和clientHeight是如何计算的?
EN

Stack Overflow用户
提问于 2022-01-17 02:07:11
回答 1查看 122关注 0票数 0

运行此代码段时,您将看到以下内容(至少在Chrome 97.0.4692.71中如此):

  1. 在页面加载上,clientHeightscrollHeight比1行所需的要多。
  2. 除非显式设置,否则line-heightundefined。设置line-height会影响初始clientHeightscrollHeight值。
  3. 输入1行中断不会改变clientHeightscrollHeight。它们似乎有足够的空间来初始化2行。
  4. 输入2行中断会像预期的那样增加scrollHeight,但它并不等于textHeight
  5. 输入足够多的字符来包装会导致scrollHeight增加,但是没有添加到文本中的换行符(也就是说,textHeight不会改变)。

用来得出观察到的clientHeightscrollHeight值的计算是什么?

代码语言:javascript
运行
复制
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;
}
代码语言:javascript
运行
复制
textarea {
  all: unset;
  background-color: #ddd;
  overflow-y: hidden;
  overflow-x: hidden;
  overflow-wrap: break-word;
  font-size: medium;
}
代码语言:javascript
运行
复制
<textarea></textarea>

EN

回答 1

Stack Overflow用户

发布于 2022-01-17 02:29:39

除非定义,否则line-height将使用用户代理样式表(根据MDN,桌面浏览器通常使用1.2 )。有了这些信息,结果应该更有意义。

clientHeight总是2 * line-height

scrollHeightline-height * lines

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70735796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档