1. 程式人生 > >字型顏色動態變換

字型顏色動態變換

js設定html字型顏色動態變換

一、如果只是兩種顏色輪換

<head>
<script>
function changecolor()
{
    var b=document.getElementById("a").style.color;
    if(b=="red"){document.getElementById("a").style.color="yellow";}
    else {document.getElementById("a").style.color="red";}
}
setInterval("changecolor()"
,250)//設定迴圈速度 </script> </head> <body> <h4 id="a"style="color:red;"> 你好!很高興見到你!</h4> </body>

 

效果看右邊:錄製螢幕的工具有點卡,正常的是紅黃交替。 這種情況適合少的,多了就麻煩了。

二、建立陣列

1、

<html>
<head>
<script>
function changecolor()
{
   var col=new Array();
col[
0]="yellow"; col[1]="blue"; col[2]="green"; col[3]="gray"; document.getElementById('a').style.color=col[parseInt(Math.random() * col.length)]; } setInterval("changecolor()",250) </script> </head> <body onload="changecolor()"> <h4 id="a"style="color:red;">好久不見!</h4> </body>
</html>

 

效果看右邊:Math.random()函式產生0.0~1.0的隨機數,與陣列的長度相乘取整。 2、也可以用split()函式切割字串做成陣列
function changeColor()
{ 
var color="blue|gray|green|red|yellow|white"; 
color=color.split("|"); //在“|”處切割
document.getElementById("a").style.color=color[parseInt(Math.random() * color.length)]; 
} 
setInterval("changeColor()",250); 

 

謝謝瀏覽!