简体   繁体   English

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

[英]Adding random fonts to each element of class

Been trying to make it so that each div with the class .book gets allocated a random font from an array. 一直在努力使.book类的每个div从数组中分配一个随机字体。 This is my code so far 到目前为止,这是我的代码

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; 

The error I am getting is: Uncaught TypeError: Cannot set property 'fontFamily' of undefined 我得到的错误是: Uncaught TypeError: Cannot set property 'fontFamily' of undefined

Anyone know what I am doing wrong? 有人知道我在做什么错吗?

$(".book") returns a jquery array. $(".book")返回一个jquery数组。 eg to set the first you would use: 例如,设置您将要使用的第一个:

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

You need to loop through $(".book") to get the DOM elements: 您需要遍历$(".book")以获得DOM元素:

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

(unless you meant to set them all to the same font, in which case set randomfont outside the loop). (除非您打算将它们全部设置为相同的字体,在这种情况下,请在循环外部设置randomfont )。

That's because you are trying to set the fontFamily directly on the jQuery object instead of the DOM element. 那是因为您试图直接在jQuery对象而不是DOM元素上设置fontFamily。

Either use jQuery's css method or use get / array selector to retrieve the DOM element. 使用jQuery的css方法或使用get / array选择器检索DOM元素。

On the other hand you want to do that on each element, so you need to use each like this: 另一方面,您想对每个元素执行此操作,因此需要像这样使用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> 

hope this will help. 希望这会有所帮助。 just call the id using the document.getElementById('') and then set the font value. 只需使用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