本文實例講述了JS實現的按鈕點擊顏色切換功能。分享給大家供大家參考,具體如下:
先來看看運行效果:
具體代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>www.gxlcms.com 點擊切換按鈕顏色</title> </head> <body> <button id="btn1" onclick="btn(1)">按鈕1</button> <button id="btn2" onclick="btn(2)">按鈕2</button> <button id="btn3" onclick="btn(3)">按鈕3</button> <script> //設置背景顏色 //如果設置參數函數會節省函數數量吧 //設置flag+參數函數 flag = "btn1"; function btn1(){ document.getElementById("btn2").style.color = "black"; document.getElementById("btn3").style.color = "black"; document.getElementById("btn1").style.color = "red"; } function btn2(){ document.getElementById("btn1").style.color = "black"; document.getElementById("btn2").style.color = "red"; document.getElementById("btn3").style.color = "black"; } function btn3(){ document.getElementById("btn1").style.color = "black"; document.getElementById("btn2").style.color = "black"; document.getElementById("btn3").style.color = "red"; } function btn(num){ if(num == 1){ document.getElementById(flag).style.color = "black"; document.getElementById(flag).style.backgroundColor = "white"; document.getElementById("btn1").style.color = "red"; document.getElementById("btn1").style.backgroundColor = "blue"; flag = "btn1"; } if(num == 2){ document.getElementById(flag).style.color = "black"; document.getElementById(flag).style.backgroundColor = "white"; document.getElementById("btn2").style.color = "red"; document.getElementById("btn2").style.backgroundColor = "blue"; flag = "btn2"; } if(num == 3){ document.getElementById(flag).style.color = "black"; document.getElementById(flag).style.backgroundColor = "white"; document.getElementById("btn3").style.color = "red"; document.getElementById("btn3").style.backgroundColor = "blue"; flag = "btn3"; } } </script> </body> </html>
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com