每次刷新页面时,如何为一行文本生成随机字体? [英] How do I generate a random font to a line of text every time page is refreshed?

查看:155
本文介绍了每次刷新页面时,如何为一行文本生成随机字体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在每次从我的JavaScript列表中刷新我的页面时生成一个新的字体。我总共需要4种字体,而且我希望读取字体的行是实际更改的字体。我无法随时更改字体来刷新页面。任何方式,我可以用JavaScript做到这一点?这里有一些我尝试过的:

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

这似乎不起作用。我想知道我将不得不打电话给字体的ID,但是甚至有GetelementById(fontfamily)这样的东西?这也是在我的身体标签。

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

这会是更好的选择吗?我如何得到这个随机选择?

解决方案

您想要 document.getElementById(fontfamily)。style.fontFamily;

每当你想使用JavaScript来设计一个元素的样式时,使用 .style ,然后将css属性赋值。所以 font-family 变成 fontFamily background-image 变成 backgroundImage

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

http://jsfiddle.net/DZnbR/


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?

解决方案

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/

这篇关于每次刷新页面时,如何为一行文本生成随机字体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆