简体   繁体   English

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

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

I'm working on a website and I'm trying to figure out how to change the font everytime someone loads the page.我在一个网站上工作,我试图弄清楚每次有人加载页面时如何更改字体。 The content of the text would be the same, but the font would be different everytime someone visits the website.文本的内容将是相同的,但每次有人访问该网站时字体会有所不同。

Is there a way to make a specific text element cycle randomly between 7-8 fonts on a webpage?有没有办法让特定的文本元素在网页上的 7-8 fonts 之间随机循环?

I did it with three fonts, but you can use seven or eight with the same idea.我是用三个 fonts 做的,但你可以用相同的想法使用七个或八个。 First, define all fonts in the CSS:首先,在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);
}

Then make CSS variable that stores the (randomily) selected font.然后使 CSS 变量存储(随机)选择的字体。 Make also a classname that uses the font.还要创建一个使用该字体的类名。

/* 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);
}

And lastly add some JavaScript to randomily pick one font to use.最后添加一些 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);

Here is the result when I'm refreshing the site:这是我刷新网站时的结果: 字体随机变化

What you could do is have a list of the font-family declarations you can choose from and then at load time invoke a bit of Javascript that gets a random number and selects one of them.您可以做的是列出您可以从中选择的字体系列声明,然后在加载时调用一点 Javascript 获取随机数并选择其中一个。

The JS can then set a CSS variable, say --font-family, which is what is used in your style sheet(s).然后 JS 可以设置一个 CSS 变量,比如 --font-family,这是在您的样式表中使用的。

Here's a simple example:这是一个简单的例子:

 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