本文實例講述了JavaScript實作點擊按鈕切換網頁背景色的方法。分享給大家參考,具體如下:
這裡示範JavaScript用按鈕隨意變換背景顏色,每點一下按鈕,就可以隨機改變一種網頁背景顏色。顏色值事先是保存在JS的陣列裡,你在程式碼裡會發現他們,若不想要某個顏色,就替換掉即可。
運作效果截圖如下:
線上示範網址如下:
http://demo.jb51.net/js/2015/js-btn-click-rand-bgcolor-codes/
具體程式碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>通过按钮变换背景颜色</title> </head> <body> <script language="javascript"> var Arraycolor=new Array("olive","teal","red","blue","maroon","navy","lime","fuschia","green","purple","gray","yellow","aqua","white","silver"); var n=0; function turncolors(){ if (n==(Arraycolor.length-1)) n=0; n++; document.bgColor = Arraycolor[n]; } </script> <form name="form1" method="post" action=""> <p> <input type="button" name="Submit" value="变换背景" onclick="turncolors()"> </p> <p>用按钮变换背景颜色.</p> </form> </body> </html>
希望本文所述對大家JavaScript程式設計有所幫助。