繁体   English   中英

向类的每个元素添加随机字体

[英]Adding random fonts to each element of class

一直在努力使.book类的每个div从数组中分配一个随机字体。 到目前为止,这是我的代码

var fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell'];
var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
$(".book").style.fontFamily = randomfont; 

我得到的错误是: Uncaught TypeError: Cannot set property 'fontFamily' of undefined

有人知道我在做什么错吗?

$(".book")返回一个jquery数组。 例如,设置您将要使用的第一个:

$(".book")[0].style.fontFamily = 

您需要遍历$(".book")以获得DOM元素:

$(".book").each(function() {
    var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
    this.style.fontFamily = randomfont; 
});

(除非您打算将它们全部设置为相同的字体,在这种情况下,请在循环外部设置randomfont )。

那是因为您试图直接在jQuery对象而不是DOM元素上设置fontFamily。

使用jQuery的css方法或使用get / array选择器检索DOM元素。

另一方面,您想对每个元素执行此操作,因此需要像这样使用each元素:

 //const fonts = ['Gloria Hallelujah', 'Sedgwick Ave', 'Gochi Hand', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell']; const fonts = ['Helvetica', 'Arial', 'Verdana', 'Courier', 'Courier New']; $('.book').each(function(item) { const randomfont = fonts[Math.floor(Math.random() * fonts.length)]; this.style.fontFamily = randomfont; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="book">Test 1</div> <div class="book">Test 2</div> <div class="book">Test 3</div> <div class="book">Test 4</div> <div class="book">Test 5</div> <div class="book">Test 6</div> 

希望这会有所帮助。 只需使用document.getElementById('')调用ID,然后设置字体值即可。

var fonts = ['Impact,Charcoal,sans-serif', 'Sedgwick Ave', ' Helvetica', 'Patrick Hand', 'Kalam', 'Rock Salt', 'Neucha', 'Caveat Brush', 'Schoolbell'];
var randomfont = fonts[Math.floor(Math.random() * fonts.length)];
alert(randomfont);
var val=document.getElementById("book").style.fontFamily = randomfont;

暂无
暂无

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

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