簡體   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