1.点击切换颜色:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .my{ background-color: red; 100px; height: 100px; } </style> </head> <body> <div class = "my"></div> <script> var flag = true; var oMy = document.getElementsByClassName("my")[0] oMy.onclick = function(){ if (flag){ oMy.style.backgroundColor = 'green'; flag = false; }else{ oMy.style.backgroundColor = 'red'; flag = true; } } </script> </body> </html>
2.显示和隐藏显示框.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ 200px; height: 200px; background-color: red; } </style> </head> <body> <div class = "box"></div> <button class = "hide">隐藏1</button> <button>隐藏2</button> <script> var oBe = document.getElementsByClassName("box")[0]; var oHi = document.getElementsByClassName("hide")[0]; flag = true; oHi.onclick =function(){ if (flag){ oBe.style.display = "none"; flag = false; this.innerText ="显示" }else{ oBe.style.display = "block"; flag = true; this.innerText ="隐藏" } } </script> </body> </html>