JS实现按钮颜色切换效果

编程学习 2021-07-04 17:32www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了JS实现按钮颜色切换效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

<!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> 

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

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板