在此之前没接触到JS,看过此案例。在学之后,根据自己理解,写出了一个开关实例。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 7 </head> 8 <body> 9 <img id="light" src="img/light-off.png" /> 10 <input id="button" type="image" src="img/close.png" /> 11 12 13 <script> 14 window.onload=function(){ 15 //获取元素 16 var light=document.getElementById("light"); 17 var button=document.getElementById("button"); 18 19 //增加一个全局变量,用来保存开关状态。默认状态与HTML初始图片保持一致,即默认为关闭状态。 20 var open=false; 21 button.onclick=function(){ 22 if(open){ 23 this.src="img/close.png"; 24 light.src="img/light-off.png"; 25 open=false; 26 }else{ 27 this.src="img/open.png"; 28 light.src="img/light-on.png"; 29 open=true; 30 } 31 } 32 33 34 } 35 36 </script> 37 </body> 38 </html>
所需要的图片(第一种方法):
灯泡关闭
灯泡开启
第二种方法:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 7 </head> 8 <body> 9 10 <script> 11 function changeImage() 12 { 13 element=document.getElementById(\'myimage\') 14 if (element.src.match("bulbon")) 15 { 16 element.src="img/eg_bulboff.gif"; 17 } 18 else 19 { 20 element.src="img/eg_bulbon.gif"; 21 } 22 } 23 </script> 24 25 <img id="myimage" onclick="changeImage()" src="img/eg_bulboff.gif"> 26 27 <p>点击灯泡来点亮或熄灭这盏灯</p> 28 29 </body> 30 </html>
效果图:
灯泡关闭
灯泡开启
完整的代码及图片请前往GitHub 地址:https://github.com/chen2017311/JavaScript.git