Chrome 如何在JavaScript中从浏览器设置中获取字体大小?[副本]

8iwquhpp  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(135)

此问题已在此处有答案

detect browser font size(7个回答)
12天前关闭
在JavaScript中,我想获取用户的字体大小,这实际上是在浏览器的外观设置中设置的。
有可能把它写进剧本吗?

kknvjkwl

kknvjkwl1#

我试图找到一种方法来获得字体大小,这是设置在外观设置和,这里是应该工作在Chrome正确的功能。

const defaultSize = 16;

function getBrowserFontSize() {
  try {
    const element = document.createElement("button");
    element.style.display = "none";
    element.style.fontSize = "initial";
    document.body.append(element);

    const fontSizeMatch = window
      .getComputedStyle(element)
      .getPropertyValue("font-size")
      .match(/^(\d*\.?\d*)px$/);

    element.remove();

    if (!fontSizeMatch || fontSizeMatch.length < 1) {
      return defaultSize;
    }

    const result = Number(fontSizeMatch[1]);
    return !isNaN(result) ? result : defaultSize;
  } catch (e) {
    console.error(e);
    return defaultSize;
  }
}

console.log(getBrowserFontSize());

相关问题