<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>随机显示颜色</title> <style> #div1{ 100px; height: 100px; } </style> </head> <body onload="change()"> <div id="div1"></div> </body> <script> function change(){ var i=Math.random()*10; var div1=document.getElementById("div1"); if(0<i<4){ div1.style.backgroundColor="red"; } if(4<=i&&i<7){ div1.style.backgroundColor="yellow"; } if(7<=i&&i<10){ div1.style.backgroundColor="green"; } } </script> </html>