【问题标题】:Display Google Typeface at Random on Click点击时随机显示 Google 字体
【发布时间】:2018-04-02 02:19:59
【问题描述】:

我试图让我的页面上的文本在点击时随机显示颜色和字体。颜色正常,但我无法更改字体。控制台告诉我代码正在运行,但没有显示。

$(document).ready(function(){
  $('.header').click(function() { 
    $(".header").toggleClass("headerChange");
    var color = randmColor();
    $(".header").css("color", color);

    var fontType = [ "Lily Script One", "Monoton"];
    $(".header").css("fontfamily", fontType[Math.floor(Math.random()*2)]);
  });

CSS:

@import url('https://fonts.googleapis.com/css?family=Josefin+Slab');
@import url('https://fonts.googleapis.com/css?family=Lily+Script+One');

我认为这是它调用 CSS 的方式,但我是编码新手并且很难过。

【问题讨论】:

    标签: javascript css fonts


    【解决方案1】:

    在您的 html 中,您需要确保:

        <style>
        @import url('https://fonts.googleapis.com/css?family=Lily+Script+One'); 
        </style>
        <style>
        @import url('https://fonts.googleapis.com/css?family=Josefin+Slab');
        </style>
    

    你的 CSS 你不会设置字体,它会从你拥有的任何默认字体开始,然后用你的 javascript 更改为随机字体。

    【讨论】:

    • 首先,您可以在一个&lt;style&gt; 标签范围内执行此操作。其次,同样可以通过&lt;link&gt;标签链接外部CSS文件(这是更简洁的方法)。
    【解决方案2】:

    您错过了"font-family" 中的一个连字符。只需更改倒数第二行:

    $(".header").css("font-family", fontType[Math.floor(Math.random()*2)]);
    

    here 已经描述了更改 "font-family" 属性的问题。

    当然,您还应该确保您的 CSS 文件通过&lt;link&gt; 标签链接到您的 HTML 中。

    【讨论】:

    • 嗨,Karol,我更改了行以阅读您提供的文本,但它似乎不起作用。还有其他想法吗?我确实在一个单独的 css 文件中有指向 google 字体的链接,该文件链接在 html 文件中。
    猜你喜欢
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多