问题
I am trying to generate a new font every time my page is refreshed from a list in my JavaScript. I want 4 fonts total, and I want the line that reads "Font" to be the font that actually changes. I can't get the font to change at all anytime I refresh the page. Any way I can possibly do that with 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)"? 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?
回答1:
You want document.getElementById("fontfamily").style.fontFamily;
Whenever you want to style an element using JavaScript, use .style
then camelcase the css attribute. so font-family
becomes fontFamily
, background-image
becomes 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/
回答2:
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>
来源:https://stackoverflow.com/questions/21862759/how-do-i-generate-a-random-font-to-a-line-of-text-every-time-page-is-refreshed