我在一个网站上工作,我正在尝试弄清楚如何在每次有人加载页面时改变字体。文本的内容是相同的,但每次有人访问网站时,字体都会不同。
有没有办法让一个特定的文本元素在网页上的7-8种字体之间随机循环?
发布于 2021-04-16 00:01:45
我用了三种字体,但你也可以用七种或八种字体来表达同样的意思。首先,定义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);
下面是我刷新站点时的结果:
发布于 2021-04-16 00:10:49
您可以做的是有一个可供选择的字体系列声明列表,然后在加载时调用一些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
https://stackoverflow.com/questions/67110443
复制相似问题