<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>灯泡开关</title> </head> <body> <img src="images/off.png" alt="" id="light"> <div id="btn">开</div> </body> <style> #btn{ width: 70px; height: 40px; text-align: center; line-height: 40px; font-size: 18px; font-weight: bold; background: #1492ff; color: #fff; cursor: pointer; margin: 20px auto; border-radius: 5px; } #light{ display: block; width: 200px; margin: 0 auto; } </style> </html> <script> function fun(flag) { // 1.获取按钮对象 var btn = document.getElementById("btn"); // 2.获取图片对象 var light = document.getElementById("light"); // 3.绑定单击事件 btn.onclick = function() { if(flag) { // 判断如果灯是开的,则灭掉 light.src = "images/off.png"; btn.innerText = ‘开‘; flag = false; } else { // 如果灯是灭的,则打开 light.src = "images/on.png"; btn.innerText = ‘关‘; flag = true; } } } fun(false);//调用函数 </script>
图片