0

我使用getComputedStyle(element)[type], 其中 element 是我的<p>标签并且typefontSize, lineHeight, letterSpacing, fontFamilyor width。对于 fontSize 和 width,我得到数值,比如 16px 和 100%。这是我可以使用的东西,但是对于 letterSpacing 和 lineHeight 我得到normal了一个值。但我需要它作为一个数值,所以我可以加减它。我想使用 JS 来操作它。

在我的样式表中,它看起来像这样:

:root {
  --font-size: 1rem;
  --line-height: inherit;
  --letter-spacing: 0rem;
  --font-type: inherit;
  --text-width: 100%;
}

可以选择手动编写一个包含我已经设置的值的数组,然后使用它。但是我仍然会遇到 lineHeight 的问题,因为它继承了它。

这是一个例子:

const target = document.getElementById("target");
console.log(getComputedStyle(target)["lineHeight"]);
:root {
  --font-size: 1rem;
  --line-height: inherit;
  --letter-spacing: 0rem;
  --font-type: inherit;
  --text-width: 100%;
}
<p id="target"></p>

4

1 回答 1

0

如果你得到normal,我认为没有办法获得实际的数字等价物。

MDN 说

normal

取决于用户代理。桌面浏览器(包括 Firefox)使用默认值大概1.2,取决于元素的font-family.

所以你可以假设normal=>1.2但这不是一个可靠的假设。

取决于你具体做什么getClientRects可能会有用,因为它可以告诉你段落有多高。如果你保存它的内容并只给它一个字符x(然后在测量后恢复它的内容),那将告诉你该段落中一行的像素有多高,所有其他条件都相同:

const target = document.getElementById("target");
console.log(getComputedStyle(target)["lineHeight"]);
console.log(target.getClientRects()[0].height);
:root {
  --font-size: 1rem;
  --line-height: inherit;
  --letter-spacing: 0rem;
  --font-type: inherit;
  --text-width: 100%;
}
<p id="target">x</p>

不过,这是否有用取决于您在做什么。

于 2021-01-02T10:44:37.410 回答