欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS实现按钮颜色切换效果

程序员文章站 2022-07-06 20:34:27
本文实例为大家分享了使用参数函数实现按钮颜色切换的具体代码,供大家参考,具体内容如下

本文实例为大家分享了使用参数函数实现按钮颜色切换的具体代码,供大家参考,具体内容如下

<!doctype html> 
<html lang="en"> 
<head> 
  <meta charset="utf-8"> 
  <title>document</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> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。