繁体   English   中英

每次加载页面时,如何更改 web 元素的字体?

[英]How can I change the font of a web element everytime the page is loaded?

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

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

我是用三个 fonts 做的,但你可以用相同的想法使用七个或八个。 首先,在CSS中定义所有fonts:

@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);

这是我刷新网站时的结果: 字体随机变化

您可以做的是列出您可以从中选择的字体系列声明,然后在加载时调用一点 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

暂无
暂无

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

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