【问题标题】:How to change webpage background colour multiple times by clicking on the same button?如何通过单击同一个按钮多次更改网页背景颜色?
【发布时间】:2012-12-26 18:11:24
【问题描述】:

我是 JavaScript/jQuery 的绝对初学者。

我想知道我是否可以通过多次单击同一个按钮来实现可以连续切换网页的多种背景颜色的效果。

这是我在网上找到的脚本:

<script>
  $("#change-colour").click(function(){ 
  $("body").css("background-color","red");
  });
</script>

但是,使用它我只能更改一次背景颜色。我希望通过单击同一个按钮多次更改背景颜色,例如:

点击>>红色>>点击>>蓝色>>点击>>绿色>>点击>>然后回到红色

任何帮助将不胜感激。 谢谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要将颜色存储在某处,例如数组,然后只需使用递增变量来获取下一个颜色等,如下所示:

    var colors = ['red', 'blue', 'green', 'cyan'],
        i = 0;
    
    $("#change-colour").click(function(){ 
        $("body").css("backgroundColor", colors[i++]);
        if (i >= colors.length)
            i = 0;
    
    });​
    

    FIDDLE

    【讨论】:

    • 嗨,adeno,感谢您的解决方案。这就是我一直在寻找的。​​span>
    • 有点过头了,三元给定的操作是菜鸟。 i++; if (i&gt;=colors.length); i=0;
    【解决方案2】:
    var colours = ['red', 'blue', 'green'];
    var colourIndex = 0;
    
    $('#change-colour').click(function () {
        // Get the current colour from the array
        var colour = colours[colourIndex];
        // Set the background colour
        $('body').css('background-color', colour);
        // Move the counter along to the next index
        colourIndex = colourIndex + 1;
        // If the counter is pointing past the end of
        // the array, repoint it at the beginning
        if(colourIndex >= colours.length) {
            colourIndex = 0;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 2013-12-16
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2018-09-19
      • 1970-01-01
      相关资源
      最近更新 更多