【问题标题】:How do I use a dynamic Font url in a CSS style sheet如何在 CSS 样式表中使用动态字体 URL
【发布时间】:2021-07-21 22:58:51
【问题描述】:

我正在构建一个用户可以设计然后嵌入到他们自己网站上的小部件。他们可以选择的一件事是我们在 AWS 上自行托管的字体。

在初始加载期间,应用程序会访问我们的 API 以获取小部件详细信息,字体 URL 会在响应中返回。然后我们将其设置为 CSS 变量,如下所示:

HTML:

<div v-bind:style="cssProps">

Vus JS:

cssProps(){
  return {
    '--accent_color': "#" + this.$store.state.accent_color,
    '--font-url': (this.$store.state.font != null ? "https://wifiuploads.s3.amazonaws.com/" + this.$store.state.font : '"Source Sans Pro", sans-serif'),
  }
}

我遇到的主要问题是我无法像这样插入动态网址:

@font-face {
  font-family: "user_selection";
  src: url(var(--font-url));
}

我不能为字体使用静态 URL,我需要使用动态 URL 将字体加载到我的样式表中。

【问题讨论】:

  • 也许可以使用 JS 创建带有样式标签的动态@font-face 规则? CSS变量可以从JS中读取
  • 注册所有字体并在不同的类中使用它们
  • @AhmadKZX 是的,我认为这是唯一可行的方法。麻烦的是,我认为现在可能会遇到数百种字体被导入的原因。
  • @Kunukn - 感谢您为我指明了正确的方向。我有。在下面写下我的解决方案。

标签: css vue.js css-variables dynamic-url


【解决方案1】:

为了解决这个问题,我使用 Javascript 创建了一个带有字体规则的样式元素:

JS:

created(){
      var newStyle = document.createElement('style');
      newStyle.appendChild(document.createTextNode("\
      @font-face {\
          font-family: 'user_selection';\
          src: url('https://wifiuploads.s3.amazonaws.com/" + this.$store.state.font + "');\
      }\
      "));

      document.head.appendChild(newStyle);

    },

CSS:

body{
    font-family: "user_selection";
  }

【讨论】:

    猜你喜欢
    • 2020-08-09
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多