【问题标题】:Math.random/floor with a function and onclick?Math.random/floor 有一个函数和onclick?
【发布时间】:2018-04-16 07:37:37
【问题描述】:

尝试使用 math.floor/math.random JS 对象编写一个函数,该对象返回 1 到 5 之间的数字给函数,并根据每次单击按钮时的数字更改颜色,如下所示:

The result:

and my code:

每次单击按钮时,该函数只会返回函数中的最后一种颜色(深蓝色),即使我将“i = 5”设置为“i = 10”(除非我将其设置为 0)。这是因为我的 getRndInteger 函数、我的 colorFunction 还是我的 ?

【问题讨论】:

标签: javascript html button onclick


【解决方案1】:

这是完成我认为您正在努力实现的目标的代码。如果我从头开始做,我会采取一些不同的方法,但这会让你接近并让逻辑工作。

  1. 最好是复制/粘贴代码而不是屏幕截图。

  2. 您的随机调用需要在您的颜色函数中,以便在单击按钮时调用它。

  3. 对于 6 个可能的随机数 (0-5),您只有 5 个颜色选项。

  4. 对于 javascript 中的相等性检查,您使用“==”或“===”,而不是“=”

  5. 调用 Math.random 时不要忘记尾随的 ()

总之,大致的代码思路如下。

<div id="banner">Color Banner</div>
<button id="button" onclick="colorFunction()">Change Color</button>
<script>
    var x = document.getElementById("banner");
    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;  
    }
    function colorFunction() {   
    var i = getRndInteger(0, 6);
    if (i == 0) {
        x.style.backgroundColor = "teal";
        x.innerHTML = i;
    }
    if (i == 1) {
        x.style.backgroundColor = "goldenrod";
        x.innerHTML = i;
    }
    if (i == 2) {
        x.style.backgroundColor = "darkolivegreen";
        x.innerHTML = i;
    }
    if (i == 3) {
        x.style.backgroundColor = "darkslategrey";
        x.innerHTML = i;
    }
    if (i == 4) {
        x.style.backgroundColor = "darkslateblue";
        x.innerHTML = i;
    }
    if (i == 5) {
        x.style.backgroundColor = "maroon";
        x.innerHTML = i;
    }
   }
</script>

或者,您可以使用 switch 来代替 if-else 语句:

<div id="banner">Color Banner</div>
<button id="button" onclick="colorFunction()">Change Color</button>

<script>
    var x = document.getElementById("banner");

    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    }

    function colorFunction() {

        var i = getRndInteger(0, 6);

        x.innerHTML = i;

        switch (i) {
            case 0:
                x.style.backgroundColor = "teal";
                break;
            case 1:
                x.style.backgroundColor = "goldenrod";
                break;
            case 2:
                x.style.backgroundColor = "darkolivegreen";
                break;
            case 3:
                x.style.backgroundColor = "darkgrey";
                break;
            case 4:
                x.style.backgroundColor = "darkslateblue";
                break;
            case 5:
                x.style.backgroundColor = "maroon";
                break;
        }
    }
</script>

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多