多种方法实现按钮开关
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多种方法实现按钮开关相关的知识,希望对你有一定的参考价值。
<!doctype html> <html> <head> <title>your name</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> button{ width:100px; height:100px; } button.change{ background:red; } </style> </head> <body> <button>1</button> <button>2</button> <button>3</button> <button>4</button> <div>我是内容1</div> <div>我是内容2</div> <div>我是内容3</div> <div>我是内容4</div> <script> var obut=document.getElementsByTagName("button"); var odiv=document.getElementsByTagName("div"); obut[0].onclick=function(){ obut[0].className="change"; obut[1].className=""; obut[2].className=""; obut[3].className=""; odiv[0].style.display=""; odiv[1].style.display="none"; odiv[2].style.display="none"; odiv[3].style.display="none"; } obut[1].onclick=function(){ obut[0].className=""; obut[1].className="change"; obut[2].className=""; obut[3].className=""; odiv[0].style.display="none"; odiv[1].style.display=""; odiv[2].style.display="none"; odiv[3].style.display="none"; } obut[2].onclick=function(){ obut[0].className=""; obut[1].className=""; obut[2].className="change"; obut[3].className=""; odiv[0].style.display="none"; odiv[1].style.display="none"; odiv[2].style.display=""; odiv[3].style.display="none"; } obut[3].onclick=function(){ obut[0].className=""; obut[1].className=""; obut[2].className=""; obut[3].className="change"; odiv[0].style.display="none"; odiv[1].style.display="none"; odiv[2].style.display="none"; odiv[3].style.display=""; } </script> </body> </html> <script type="text/javascript" src="script.js"></script>
<!doctype html> <html> <head> <title>your name</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="jquery.js"></script> <style type="text/css"> button{ width:100px; height:100px; } button.change{ background:red; } </style> </head> <body> <button>1</button> <button>2</button> <button>3</button> <button>4</button> <div>我是内容1</div> <div>我是内容2</div> <div>我是内容3</div> <div>我是内容4</div> <script> var obut=document.getElementsByTagName("button"); var odiv=document.getElementsByTagName("div"); for(let i=0;i<4;i++){ obut[i].onclick=function(evt){ for(let j=0;j<4;j++){ if(j==i){ //alert("i:"+i+"j:"+j+"hello"); obut[j].className="change"; odiv[j].style.display=""; }else{ obut[j].className=""; odiv[j].style.display="none"; //alert("i:"+i+"j:"+j+"world"); } } } } </script> </body> </html> <script type="text/javascript" src="script.js"></script>
以上是关于多种方法实现按钮开关的主要内容,如果未能解决你的问题,请参考以下文章