简体   繁体   English

每次刷新页面时,如何为一行文本生成随机字体?

[英]How do I generate a random font to a line of text every time page is refreshed?

I am trying to generate a new font every time my page is refreshed from a list in my JavaScript. 每当我从JavaScript中的列表刷新页面时,我都试图生成一种新字体。 I want 4 fonts total, and I want the line that reads "Font" to be the font that actually changes. 我想要总共4种字体,并且我希望将显示为“ Font”的行作为实际更改的字体。 I can't get the font to change at all anytime I refresh the page. 刷新页面后,我无法完全更改字体。 Any way I can possibly do that with JavaScript? 我可以用JavaScript做到这一点吗? Here are some things I tried: 这是我尝试过的一些方法:

<script>
var fontType = [ "Arial", "Verdana", "Helvetica"];
var num;
num=Math.floor(Math.random()*3);
document.getElementById("fontfamily").src=fontType[num];
</script>

This didn't seem to work. 这似乎没有用。 I wondered I'd have to call an ID for the fonts, but is there even such a thing as "GetelementById(fontfamily)"? 我想知道是否必须为字体调用一个ID,但是是否还有诸如“ GetelementById(fontfamily)”之类的东西? This was also in my body tags. 这也在我的身体标签中。

var font = [];
font[0] = "Times New Roman";
font[1] = "Arial";
font[2] = "Helvetica";

Would this be a better option? 这会是更好的选择吗? How would I get this to randomly choose? 我如何才能随机选择?

You want document.getElementById("fontfamily").style.fontFamily; 您需要document.getElementById("fontfamily").style.fontFamily;

Whenever you want to style an element using JavaScript, use .style then camelcase the css attribute. 每当您想使用JavaScript设置元素样式时,请使用.style然后使用camelcase css属性。 so font-family becomes fontFamily , background-image becomes backgroundImage 所以font-family变成fontFamilybackground-image变成backgroundImage

var fontType = [ "Arial", "Verdana", "Helvetica"];
var num;
num=Math.floor(Math.random()*3);
document.getElementById("fontfamily").style.fontFamily =fontType[num];

http://jsfiddle.net/DZnbR/ http://jsfiddle.net/DZnbR/

Here you go : 干得好 :

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link href="https://fonts.googleapis.com/css?family=Open+Sans|Raleway|Roboto" rel="stylesheet"> <style> .Roboto{ font-family: 'Roboto', sans-serif; } .Open_Sans{ font-family: 'Open Sans', sans-serif; } .Roboto{ font-family: 'Raleway', sans-serif; } </style> </head> <body id="body"> <script> var fonts = ['Roboto', 'Open_Sans', 'Raleway']; var rand = fonts[Math.floor(Math.random() * fonts.length)]; console.log(rand); var bodyElement = document.getElementById("body"); bodyElement.className = rand; </script> </body> </html> 

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

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