亲宝软件园·资讯

展开

JS按钮点击颜色切换 JS实现的按钮点击颜色切换功能示例

spfLinux 人气:0
想了解JS实现的按钮点击颜色切换功能示例的相关内容吗,spfLinux在本文为您仔细讲解JS按钮点击颜色切换的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:JS,按钮,点击,颜色,切换,下面大家一起来学习吧。

本文实例讲述了JS实现的按钮点击颜色切换功能。分享给大家供大家参考,具体如下:

先来看看运行效果:

具体代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>www.qb5200.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程序设计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论