【问题标题】:Randomize an html tag with JavaScript [duplicate]使用 JavaScript 随机化 html 标签 [重复]
【发布时间】:2016-07-20 17:43:32
【问题描述】:

我想使用 Google Chrome 的主题颜色功能。正常语法如下所示:

<meta name="theme-color" content="#c12432">

但是我想使用 3 种不同的颜色,所以我想出了这个代码。值得一提的是,我没有使用 JavaScript 的经验,所以请告诉我代码有什么问题。我想要做的是它随机选择一个数字,并使用该数字将 content="value" 更改为下面指定的数字。

function colorchanger() {
     var x = Math.floor((Math.random() * 3) + 1);
     if (x >= 3) {
            document.getElementByName("theme-color").content = "#c12432";
        }
     if (x = 2) {
            document.getElementByName("theme-color").content = "#338fc4";
        }
     if (x = 1) {
            document.getElementByName("theme-color").content = "#d99e33";
        }
    }

【问题讨论】:

  • 按 f12,这将打开您的控制台。在您的控制台中,您可以看到诸如“未捕获的类型错误:document.getElementByName 不是函数”之类的错误,尽管它因浏览器而异,这通常是您的代码将抛出的内容以及您如何检测它。

标签: javascript html


【解决方案1】:

不是您要求的,但如果您可以访问 PHP,那么您可以使用它作为替代方案:

<?php
randomTheme() {
$themeColor[] = "#c12432"; // Color Name I.E. Red
$themeColor[] = "#338fc4"; // Color Name I.E. Blue
$themeColor[] = "#d99e33"; // Color Name I.E. Yellow
$randomThemeColor = array_rand($themeColor);

return $themeColor[$randomThemeColor];
}
?>

然后在您的元标记中:&lt;meta name="theme-color" content="&lt;?php echo randomTheme(); ?&gt;"&gt;

您也可以像这样制作函数,但我更喜欢较长的版本,这样您就可以通过它们旁边的名称来注意十六进制颜色是什么。此解决方案适用于几种颜色,但第一种解决方案适用于大列表。

 <?php
    randomTheme() {
    $themeColor = array("#c12432","#338fc4","#d99e33");
    $randomThemeColor = array_rand($themeColor);

    return $themeColor[$randomThemeColor];
    }
    ?>

【讨论】:

    【解决方案2】:

    所以首先你可以像这样组合你的 if 语句来节省运行时间:

     if (x >= 3) {
            document.getElementByName("theme-color").content = "#c12432";
        }
     else if (x == 2) {
            document.getElementByName("theme-color").content = "#338fc4";
        }
     else if (x == 1) {
            document.getElementByName("theme-color").content = "#d99e33";
        }
    

    另外,如果您注意到我将x = 2 和x = 3 更改为x == 2 和x == 3,因为一个等号是赋值,而双等号是比较运算符。因此,当您认为您正在检查 x = 2 时,您实际上是在将 x 设置为 2。

    还要考虑到 cmets 中添加的内容,这些只是明显的 JavaScript 错误。

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 2022-01-10
      • 2021-05-23
      • 2018-06-27
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多