简体   繁体   English

如何在 CSS 样式表中使用动态字体 url

[英]How do I use a dynamic Font url in a CSS style sheet

I'm building a widget which users can design and then embed on their own website.我正在构建一个用户可以设计然后嵌入到他们自己的网站上的小部件。 One thing they can choose is the font, which we self host on AWS.他们可以选择的一件事是我们在 AWS 上自行托管的字体。

During the initial load, the app hits our API for the widget details, the font URL is returned in the response.在初始加载期间,应用程序点击我们的 API 以获取小部件详细信息,字体 URL 在响应中返回。 We are then setting this as a CSS variable like so:然后我们将其设置为 CSS 变量,如下所示:

HTML: HTML:

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

Vus JS: VS 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'),
  }
}

The main issue I have come across it I cannot interpolate a dynamic url like this:我遇到的主要问题是我无法像这样插入动态 url:

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

I cannot use a static url for the fonts, I need away to load fonts into my stylesheets with a dynamic URL. I cannot use a static url for the fonts, I need away to load fonts into my stylesheets with a dynamic URL.

To resolve I created a style element with a font-face rule using Javascript:为了解决这个问题,我使用 Javascript 创建了一个带有字体规则的样式元素:

JS: 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: CSS:

body{
    font-family: "user_selection";
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM