【问题标题】:Css/js Include user uploaded fontCss/js 包含用户上传的字体
【发布时间】:2020-04-16 17:03:20
【问题描述】:

在我的应用中,我允许用户上传各种格式的自定义字体(如 ttf、otf 等)。

这些文件存储在服务器上,可通过简单的 GET 请求访问。

我建立了一个选择,其中包含这些字体,在选择时,一些元素的字体应该更改为该字体。

我应该如何改变元素的样式? 据我所知有两种方法:

  1. 遍历自定义字体并通过链接元素包含该字体。 但是,这种方法存在缺陷,因为我无法可靠地检测字体系列名称,因此我无法设置要设置样式的元素的字体系列样式。

  2. 使用 @font-face 注入 css 规则。 这种方法可行,但它存在一定的安全漏洞,因为我会将用户生成的 css 注入浏览器。

我使用 vuejs,所以我可以安全地将 css 附加到单个元素,但据我所知,@font-face 不能通过在每个元素处重新定义它来工作。是否有一些像 font: url(src) 这样的属性可以用来做这个?

提前致谢

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    我不知道您为什么在选项 2 中说“用户生成的 css”。它不会是用户生成的 css。您将自己生成这个 css。比这更好的是,您从自己的 API 调用字体,因此从用户到另一个用户的 css 的唯一区别是您可以保护一些参数。

    @font-face 允许您在属性font-family 中为您的字体指定任何名称。您可以为您的字体系列创建一个名称模式,并动态地为您的元素提供这些字体名称。

      function changeFont() {
         // dynamic number. Create your own logic to generate this number
        const i = 123;
    
        // put your API path to the dinamic font file. I'm using a demo font
        const fontsource = "https://fonts.gstatic.com/s/robotoslab/v11/BngbUXZYTXPIvIBgJJSb6s3BzlRRfKOFbvjoa4Omb2Rm.ttf";
        
        const style = document.createElement('style');
        style.innerHTML = `
          @font-face {
            font-family: customfont${i};
            src: url(${fontsource});
          }
        `;
    
        document.head.appendChild(style);
    
        const p = document.getElementById('text');
    
        p.style.fontFamily = 'customfont' + i;
      }
    <p id="text">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <button onclick="changeFont()">Click me</button>

    【讨论】:

    • 我认为这是最好的答案。对于使用此方法的其他人,请仅使用完全保存的 'fontsource' 值,因为这种方法有 xss 的危险。但是如果一个人自己生成这个链接,一个应该被保存。
    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2013-05-25
    • 2020-04-01
    • 2017-05-26
    • 2016-05-30
    • 2015-04-07
    相关资源
    最近更新 更多