随机背景颜色变化 [英] Random Background Color Change

查看:114
本文介绍了随机背景颜色变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击按钮时将主体背景颜色更改为随机颜色.

I am trying to change the body background-color to a random color on a button click.

<script>
$( document ).ready(function() {
    $('.SpecButton').click(function() {
        $('body').css('background-color',"<?php 
            $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
            $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
            echo $color;
                ?>");
            });
        });     
</script>

问题是第一次单击会更改背景颜色,但是第二次尝试则不会.

The problem is the first click changes background color, but the second try Does not.

推荐答案

您应该在javascript中进行随机数生成.由于PHP代码是服务器端的代码,因此它只会设置一次随机数,而使用javascript,每次单击按钮都可以获取新的随机数.

You should do the random number generation within javascript. Since PHP code is server side it will only set the random number once, whereas with javascript you can get new random numbers each time the button is clicked.

$( document ).ready(function() {
    $('.SpecButton').click(function() {
        var color = '#'+Math.floor(Math.random()*16777215).toString(16);
        $('body').css('background-color', color );
    });
});     

在这里拨弄: http://jsfiddle.net/TQ3hV/

或者,如果您可以使用RGB颜色,则此方法可能最容易理解,而且最简洁:

Or if you are ok with RGB colors, this method is probably easiest and cleanest to understand:

var color = 'rgb(' + Math.floor(Math.random() * 255) + ',' 
                   + Math.floor(Math.random() * 255) + ','
                   + Math.floor(Math.random() * 255) + ')';

在这里拨弄: http://jsfiddle.net/TQ3hV/1/

随机颜色生成器的来源: http://www.paulirish .com/2009/random-hex-color-code-snippets/

Source of random color generators: http://www.paulirish.com/2009/random-hex-color-code-snippets/

这篇关于随机背景颜色变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆