【问题标题】:Adding random fonts to each element of class向类的每个元素添加随机字体
【发布时间】:2017-09-04 08:09:13
【问题描述】:

一直在努力使每个具有 .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").css("font-family", randomfont);
  • 请张贴您的html

标签: javascript jquery css arrays


【解决方案1】:

$(".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)。

【讨论】:

    【解决方案2】:

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

    要么使用 jQuery 的 css 方法,要么使用 get/数组选择器 来检索 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>

    【讨论】:

      【解决方案3】:

      希望这会有所帮助。只需使用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;
      

      【讨论】:

      • 不会像 OP 想要的那样由 class 而不是 id 设置。言下之意就是要设置多个元素,ID应该是唯一的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 2012-11-13
      • 2018-04-28
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      相关资源
      最近更新 更多