CSS/JS:通过 API 获取浏览器默认字体大小,而不是

发布于 2025-01-21 04:05:23 字数 822 浏览 1 评论 0原文

我有一个角度分量将用于两个不同的应用程序。 在一个应用程序中,html 字体大小为 100%(默认为 16px,但会随浏览器默认字体大小而变化 - 所以基本上无论用户选择什么)。

在另一个应用程序中,html 字体大小将设置为 16px。我无法改变这一点。 因此,在我的组件中使用“rem”将不会响应两个应用程序的用户字体设置。

有没有办法通过任何 JS API 或 CSS 属性来访问浏览器的默认字体大小?

这将是一个解决方案,但它可能会导致布局跳跃。所以我不太喜欢这个解决方案。

const getDefaultFontSize = () => {
const html = document.querySelector('html');

const initialFontSize = window
    .getComputedStyle(html)
    .getPropertyValue('font-size');

html.style.fontSize = 'unset';

const fontSizeMatch = window
    .getComputedStyle(html)
    .getPropertyValue('font-size')
    .match(/\d+/);

html.style.fontSize = initialFontSize;

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

const result = Number(fontSizeMatch[0]);
return !isNaN(result) ? result : null;

};

I have an angular component that will be used in two diffrent applications.
In one application, there will be a html-font size of 100% (16px as default but changing with the browsers default font size - so basicly whatever the user will choose).

In the other application the html-font size will be set to 16px. I can not change this.
So using "rem" in my component will not be rsponsive with the users font-setting for both applications.

Is there a way to access the browsers default font size by any JS API or CSS Property?

This would be a solution but it could cause layout jumps. So I do not really like this solution.

const getDefaultFontSize = () => {
const html = document.querySelector('html');

const initialFontSize = window
    .getComputedStyle(html)
    .getPropertyValue('font-size');

html.style.fontSize = 'unset';

const fontSizeMatch = window
    .getComputedStyle(html)
    .getPropertyValue('font-size')
    .match(/\d+/);

html.style.fontSize = initialFontSize;

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

const result = Number(fontSizeMatch[0]);
return !isNaN(result) ? result : null;

};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文