[英]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.