【问题标题】:How can I change the font of a web element everytime the page is loaded?每次加载页面时如何更改 Web 元素的字体?
【发布时间】:2021-07-10 14:34:27
【问题描述】:

我正在开发一个网站,并试图弄清楚每次有人加载页面时如何更改字体。文本的内容是相同的,但每次有人访问该网站时字体会有所不同。

有没有办法让特定的文本元素在网页上的 7-8 种字体之间随机循环?

【问题讨论】:

  • 资料不足,无法给出详细解答,可以看CSS variables开始。
  • @Teemu - 链接断开
  • @ProfessorAbronsius 不适合我?它可以流畅地导航到 MDN CSS 变量页面。
  • 多么奇怪 - 现在工作了〜正在给 404
  • @Teemu 您还需要什么信息?我正在寻找一种方法,让文本元素的字体系列在加载网页时在 7-8 种字体之间随机交替,因此对于访问该网站的每个人来说,字体看起来都不同。

标签: javascript html css fonts responsive-design


【解决方案1】:

我是用三种字体做的,但你可以用七种或八种来实现同样的想法。首先,在 CSS 中定义所有字体:

@font-face {
    font-family: RandomFont1;
    src: url(./font1.woff);
}
@font-face {
    font-family: RandomFont2;
    src: url(./font2.woff);
}
@font-face {
    font-family: RandomFont3;
    src: url(./font3.woff);
}

然后创建 CSS 变量来存储(随机)选择的字体。还要创建一个使用该字体的类名。

/* this stores the selected font */
:root {
    --randomFont: RandomFont1;
}

/* all elements that have this class will use the selected font */
.random-font {
    font-family: var(--randomFont);
}

最后添加一些 JavaScript 来随机选择一种字体来使用。

function randomInteger(min, max) {
    return Math.floor(Math.random() * (max-min+1) + min);
}

// if you have seven fonts, replace 3 in the next line with 7
var fontIndex = randomInteger(1, 3);
document.documentElement.style.setProperty("--randomFont", "RandomFont"+fontIndex);

这是我刷新网站时的结果:

【讨论】:

    【解决方案2】:

    你可以做的是列出你可以从中选择的字体系列声明,然后在加载时调用一些 Javascript,获取一个随机数并选择其中一个。

    然后,JS 可以设置一个 CSS 变量,比如 --font-family,它是在您的样式表中使用的。

    这是一个简单的例子:

    const fontFamilies = ["Arial, Helvetica, sans-serif", "'Times New Roman', serif", "Courier, monospace" ];
    const i = Math.floor(Math.random() * fontFamilies.length);
    document.body.style.setProperty('--font-family', fontFamilies[i]);
    body {
      font-family: var(--font-family);
    }
     Some text to show change in font-family

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多