为了账号安全,请及时绑定邮箱和手机立即绑定

CSS/js 包含用户上传的字体

CSS/js 包含用户上传的字体

牛魔王的故事 2024-01-03 17:10:00
在我的应用程序中,我允许用户上传各种格式的自定义字体(如 ttf、otf 等)。这些文件存储在服务器上,可以通过简单的 GET 请求进行访问。我构建了一个选择,其中包含这些字体,选择后,某些元素的字体应更改为该字体。我应该如何更改元素的样式?据我所知有2种方法:循环遍历自定义字体并通过链接元素包含该字体。然而,这种方法是有缺陷的,因为我无法可靠地检测字体系列名称,因此我无法设置我想要设置样式的元素的字体系列样式。使用 @font-face 注入 css 规则。这种方法可行,但它有明显的安全漏洞,因为我会将用户生成的 css 注入浏览器中。我使用 vuejs,所以我可以安全地将 css 附加到各个元素,但据我所知 @font-face 不能通过在每个元素上重新定义它来工作。是否有一些像 font: url(src) 这样的属性我可以使用?提前致谢
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

我不知道你为什么在选项 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>


查看完整回答
反对 回复 2024-01-03
  • 1 回答
  • 0 关注
  • 35 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信