<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>随机色</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> // function get_random_color() { //方法2不能用 // var letters = '0123456789ABCDEF'.split(''); // var color = '#'; // for (var i = 0; i < 6; i++ ) { // color += letters[Math.round(Math.random() * 15)]; // } // return color; // } // $(".random").each(function() { // $(this).css("background-color", get_random_color()); // }); $(function() { //方法一 $(".random").each(function() { var random = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')'; $(this).css("background-color", random); }); }); </script> </head> <body> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> <div class="random">随机色</div> </body> </html>