本文實例講述了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程序設計有所幫助。